Refactor a PL/pgSQL function to return the output of various SELECT queries

后端 未结 4 1261
执笔经年
执笔经年 2020-11-22 00:05

I wrote a function that outputs a PostgreSQL SELECT query well formed in text form. Now I don\'t want to output a text anymore, but actually run the generated <

4条回答
  •  旧巷少年郎
    2020-11-22 00:16

    You'll probably want to return a cursor. Try something like this (I haven't tried it):

    CREATE OR REPLACE FUNCTION data_of(integer)
      RETURNS refcursor AS
    $BODY$
    DECLARE
          --Declaring variables
          ref refcursor;
    BEGIN
          -- make sure `sensors`, `type`, $1 variable has valid value
          OPEN ref FOR 'SELECT Datahora,' || sensors ||
          ' FROM ' || type ||
          ' WHERE nomepcd=' || $1 ||' ORDER BY Datahora;';
          RETURN ref;
    END;
    $BODY$
    LANGUAGE 'plpgsql' VOLATILE;
    ALTER FUNCTION data_of(integer) OWNER TO postgres;
    

提交回复
热议问题