From: Frank van Vugt <ftm.van.vugt@foxi.nl>
To: Joost Kraaijeveld <J.Kraaijeveld@Askesis.nl>
Cc: pgsql-interfaces@postgresql.org
Subject: Re: plpgsql howto question
Date: Thu, 23 Dec 2004 16:27:20 +0100
Message-ID: <200412231627.20577.ftm.van.vugt@foxi.nl> (raw)
In-Reply-To: <A3D1526C98B7C1409A687E0943EAC41001EB16@obelix.askesis.nl>
References: <A3D1526C98B7C1409A687E0943EAC41001EB16@obelix.askesis.nl>
Hi Joost,
> What is the correct way of doing this?
As 'always', there's more than one way of doing this, for example
- selecting into a var and returning that var
- selecting into a record and returning the proper field of that record
- return the proper values immediately
- use 'plain' sql in combination with a case statement
Some examples:
CREATE OR REPLACE FUNCTION getcustomername(text, int4)
RETURNS text AS
'
DECLARE
my_person TEXT;
my_company RECORD;
BEGIN
IF $2 = 1 THEN
SELECT INTO my_person lastname FROM person WHERE objectid = $1;
RETURN my_person;
ELSIF $2 = 2 THEN
SELECT INTO my_company name1 from company WHERE objectid = $1;
RETURN my_company.name1;
END IF;
END
' LANGUAGE 'plpgsql' VOLATILE;
*****
CREATE OR REPLACE FUNCTION getcustomername(text, int4)
RETURNS text AS
'
DECLARE
my_id ALIAS FOR $1;
my_type ALIAS FOR $2;
BEGIN
IF my_type = 1 THEN
RETURN my_person lastname FROM person WHERE objectid = my_id;
ELSIF my_type = 2 THEN
RETURN name1 from company WHERE objectid = my_id;
END IF;
END
' LANGUAGE 'plpgsql' VOLATILE;
*****
SELECT CASE
WHEN type = 1 THEN (SELECT person)
WHEN type = 2 THEN (SELECT company)
ELSE null
END;
(albeit this is not plpgsql anymore)
Obviously you want to choose one of the approaches ;)
NB. Prettige kerstdagen alvast !
--
Best,
Frank.
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-interfaces@postgresql.org
Cc: ftm.van.vugt@foxi.nl, J.Kraaijeveld@Askesis.nl
Subject: Re: plpgsql howto question
In-Reply-To: <200412231627.20577.ftm.van.vugt@foxi.nl>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox