Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an error "record type has not been registered" in postgresql. What is wrong?

Tags:

sql

postgresql

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?

like image 771
Kores Avatar asked Jun 14 '16 14:06

Kores


People also ask

How do I create a record type in PostgreSQL?

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.

What is a Postgres tuple?

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.


1 Answers

rec is an untyped record, so replace SELECT (rec).* with VALUES (rec.CustomerID, rec.S).

like image 118
Ezequiel Tolnay Avatar answered Oct 17 '22 00:10

Ezequiel Tolnay