I am new to PostgreSQL and I am running into a few problems getting it to do what I want.
I need to build a function that would accept several variables, perform several queries internally and then return a data set that is composed of several rows and several columns. I've built several test functions to get a better grasp of Postgres' functionality, here is one:
CREATE OR REPLACE FUNCTION sql_with_rows11(id integer) RETURNS character varying AS $BODY$
declare vid integer;
declare vendor character varying;
BEGIN
vid := (select v_id from public.gc_alerts where a_id = id);
vendor := (select v_name from public.gc_vendors where v_id = vid);
RETURN vendor;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION sql_with_rows11(integer)
OWNER TO postgres;
I know that I can combine this into one query, but this is more of a practice exercise. This works fine and I get the vendor name. However, now I need to return more than one column from the gc_vendors table.
In end, I will need to build a function that will return columns from several tables based on subqueries. I've looked into creating a resultset function, but I believe it only returns one row at a time. I also looked into returning setof type, but that seems to be limited to a table that exists.
--------------EDIT
Hey guys, thanks for the help. I changed the function to the following:
CREATE OR REPLACE FUNCTION sql_with_rows14(IN v_uid character varying, IN lid integer)
RETURNS table (aid int, aname character varying) AS $BODY$
declare aid integer;
declare aname character varying;
BEGIN
sql_with_rows14.aid := (select a_id from public.gc_alerts where v_id = sql_with_rows14.v_uid);
sql_with_rows14.aname := (select a_name from public.gc_alerts where a_id = sql_with_rows14.aid);
RETURN;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
I also tried it with RETURN NEXT, but same results.
When I query it, if the query returns only one row, it works fine. However it doesn't work for multiple rows. I also tried something like this, with same results. Can you guys help again?
Tried this too: BEGIN sql_with_rows14.aid := (select a_id from public.gc_alerts); sql_with_rows14.aname := (select a_name from public.gc_alerts);
RETURN NEXT;
END;