Reputation: 41
I want to make a Function in postgreSQL that reads the result of a query with a cursor and returns the result in a table. I am not very familiar with cursors but I have make an effort with no result. The output was a blank table. Here is my code:
CREATE OR REPLACE FUNCTION getquery()
RETURNS TABLE(ID INT, Totalprice DECIMAL) AS $$
DECLARE
query_cursor CURSOR FOR SELECT CustomerID, TotalDue from SalesOrderHeader where TotalDue =( select max(TotalDue) from SalesOrderHeader);
BEGIN
OPEN query_cursor;
CLOSE query_cursor;
RETURN;
END;$$
LANGUAGE plpgsql;
Upvotes: 3
Views: 9246
Reputation: 32199
You don't need a CURSOR
at all to do this, you don't even need a function. But if you really want a CURSOR
then you have to FETCH
rows from it and return the results. You have to returns the results as a SETOF sometype
because you can not combine a CURSOR
with RETURNS TABLE
. In general, that looks like this:
CREATE TYPE soh AS (ID integer, Totalprice decimal);
CREATE FUNCTION getquery() RETURNS SETOF soh AS $$
DECLARE
query_cursor CURSOR FOR SELECT CustomerID, TotalDue FROM SalesOrderHeader
WHERE TotalDue = (select max(TotalDue) from SalesOrderHeader);
rec soh;
BEGIN
OPEN query_cursor;
FETCH query_cursor INTO rec.ID, rec.Totalprice; -- Read a row from the cursor
WHILE FOUND LOOP
RETURN NEXT rec; -- Return the data to the caller
FETCH query_cursor INTO rec.ID, rec.Totalprice; -- Keep on reading rows
END LOOP;
CLOSE query_cursor;
RETURN;
END;
$$ LANGUAGE plpgsql;
However, your query will return only a single row so the LOOP
is not necessary here. And your query will be more efficient like so:
SELECT CustomerID, TotalDue FROM SalesOrderHeader
ORDER BY TotalDue DESC LIMIT 1;
Upvotes: 3