Re: Function to return a multiple colmn table or view

From: Richard Huxton <dev(at)archonet(dot)com>
To: "Wilkinson, Jim" <Jim(dot)Wilkinson(at)cra-arc(dot)gc(dot)ca>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Function to return a multiple colmn table or view
Date: 2007-04-20 14:32:28
Message-ID: 4628CEFC.7020801@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Wilkinson, Jim wrote:
> I am new to psql , so please be patient !
>
> Can someone please provide a small quick example of a a function that
> take 1 paramater and based on that parameter, returns a table or view ?
>
> Etc .... Note this is just a abstract of the functon, not a working
> function call !!!
>
> Create function viewtest( start_month)
>
> If $1 = 'April'
> Then
> Select * from april_view;
> Return ;

CREATE TABLE month_data (md_year int4, md_month int4, md_data text);
CREATE VIEW jan_view AS SELECT * FROM month_data WHERE md_month=1;

CREATE FUNCTION viewtest(startmonth int) RETURNS SETOF month_data AS $$
DECLARE
sql text;
r record;
BEGIN
IF startmonth = 1 THEN
sql := 'SELECT * FROM jan_view';
ELSE
sql := 'SELECT * FROM month_data';
END IF;
FOR r IN EXECUTE sql LOOP
RETURN NEXT r;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;

HTH
--
Richard Huxton
Archonet Ltd

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Dmitry Turin 2007-04-20 14:49:08 Re: We all are looped on Internet: request + transport = invariant
Previous Message Wilkinson, Jim 2007-04-20 14:13:20 Function to return a multiple colmn table or view