Postgresql – Postgres Procedure Returns Table

postgresqlquery

We have a table structure returned by this function:

RETURNS TABLE (ticker VARCHAR,
           current_recommendation INTEGER,
           previous_approved_recommendation INTEGER,
           date_appended TEXT,
           suggested_recommendation INTEGER,
           date_suggested TEXT,
           suggested_by VARCHAR,
           approved_recommendation INTEGER,
           date_accepted TEXT,
           approved_by VARCHAR,
           recommendation_status INTEGER
           )

On certain conditions, rather than returning values, we want to return just the first & last values, and everything else is NULL.

v_select := 'SELECT ''' || p_ticker || ''',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,' || v_status;

But it is not working:

ERROR:  structure of query does not match function result type
DETAIL:  Returned type text does not match expected type character varying in column 1.

Any help would be great. We are all kind of new at Postgres, after migrating some thing from ORacle.

Best Answer

I suppose you can solve it by using an explicit cast.

CREATE FUNCTION test(tic text)
RETURNS TABLE (foo VARCHAR, bar int)
AS $$
DECLARE
  sql text;
BEGIN
  sql := 'SELECT ''' || tic || ''', NULL';
  RETURN QUERY EXECUTE sql;
END
$$
LANGUAGE plpgsql;

SELECT test('A');

ERROR: structure of query does not match function result type DETAIL: Returned type text does not match expected type character varying in column 1.

CREATE FUNCTION test1(tic text)
RETURNS TABLE (foo VARCHAR, bar int)
AS $$
DECLARE
  sql text;
BEGIN
  sql := 'SELECT ''' || tic || '''::VARCHAR, NULL::int';
  RETURN QUERY EXECUTE sql;
END
$$
LANGUAGE plpgsql;

SELECT test1('A');
| test1 |
| :---- |
| (A,)  |

db<>fiddle here