CREATE OR REPLACE FUNCTION get_biggest_order()
RETURNS TABLE(CustomerID int,Sum float) AS
$$
DECLARE
rec RECORD;
mycursor CURSOR FOR WITH TOTAL(TotalPerCustomer) AS (SELECT SUM(TotalDue) FROM SalesOrderHeader GROUP BY SalesOrderHeader.CustomerID),
MAX(Max) AS (SELECT MAX(TotalPerCustomer) FROM TOTAL)
SELECT SalesOrderHeader.CustomerID,SUM(TotalDue) AS S FROM SalesOrderHeader,MAX GROUP BY SalesOrderHeader.CustomerID,Max HAVING SUM(TotalDue)=Max;
BEGIN
CREATE TEMP TABLE Results2(CustomerID int,Sum float);
-- Open the cursor
OPEN mycursor;
LOOP
-- fetch row into the film
FETCH mycursor INTO rec;
-- exit when no more row to fetch
EXIT WHEN NOT FOUND;
-- build the output
INSERT INTO Results2 SELECT (rec).*;
END LOOP;
-- Close the cursor
CLOSE mycursor;
RETURN QUERY EXECUTE 'SELECT * FROM Results2';
END; $$
LANGUAGE plpgsql;
SELECT get_biggest_order();
Getting the following error in Postgres:
ERROR: record type has not been registered
CONTEXT: SQL statement "INSERT INTO Results2 SELECT (rec).*"
PL/pgSQL function get_biggest_order() line 17 at SQL statement
********** Error **********
ERROR: record type has not been registered
SQL state: 42809
Context: SQL statement "INSERT INTO Results2 SELECT (rec).*"
PL/pgSQL function get_biggest_order() line 17 at SQL statement
I am trying to return the query within the cursor in table format using the cursor. Apparently something is wrong with the record type variable and it cannot insert it into the temp table which i want to return using the function. What is wrong?
We can declare a record type variable by simply using a variable name followed by the record keyword. Syntax: variable_name record; We can use the dot notation (.) to access any field from the record type variable.
A tuple is PostgreSQL's internal representation of a row in a table. A single row may have many tuples representing it, but only one of these tuples will be applicable at any single point in time.
rec
is an untyped record, so replace SELECT (rec).*
with VALUES (rec.CustomerID, rec.S)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With