Re: Question on RETURNS TABLE example in PostgreSQL documentation

From: Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com>
To: Yan Cheng Cheok <yccheok(at)yahoo(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Question on RETURNS TABLE example in PostgreSQL documentation
Date: 2010-02-22 04:47:26
Message-ID: 162867791002212047s5fff769eq32bbd3f9bf4f62f2@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hello

2010/2/22 Yan Cheng Cheok <yccheok(at)yahoo(dot)com>:
> The following code snippet are picked from PostgreSQL documentation :
> http://www.postgresql.org/docs/current/static/plpgsql-declarations.html
>
> CREATE FUNCTION extended_sales(p_itemno int) RETURNS TABLE(quantity int, total numeric) AS $$
> BEGIN
>    RETURN QUERY SELECT quantity, quantity * price FROM sales WHERE itemno = p_itemno;
> END;
> $$ LANGUAGE plpgsql;
>
> I would like modify the following function behavior slightly :
>
> (1) Only return TABLE(quantity int, total numeric), if there is at least one row meet condition WHERE itemno = p_itemno
>
> (2) If not, create the row, and return TABLE(quantity int, total numeric)
>
> The only way I can think of is :
>
> The only way I can think of to achieve (1) is :
>
> LOOP
>        SELECT quantity, quantity * price FROM sales WHERE itemno = p_itemno;
>
>        -- Fall into creation code block.
>        EXIT WHEN NOT FOUND;
>
>        RETURN QUERY SELECT quantity, quantity * price FROM sales WHERE itemno = p_itemno;
> END LOOP;
>

RETURN QUERY isn't final statement in procedure.

so you can

RETURN QUERY first_query;
IF NOT FOUND THEN
RETURN QUERY try_some_else
END IF;
RETURN; -- final return, go out

Regards
Pavel Stehule

> But that will be two duplicated SELECT statement. Inefficient, right?
>
> Thanks and Regards
> Yan Cheng CHEOK
>
>
>
>
>
> --
> Sent via pgsql-general mailing list (pgsql-general(at)postgresql(dot)org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-general
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message AI Rumman 2010-02-22 06:30:46 change path of /tmp/.s.PGSQL.5432
Previous Message Merlin Moncure 2010-02-22 03:32:29 Re: Asynchronous queries - processing listen (notify) in a procedural language