Use text output from a function as new query

后端 未结 2 510
星月不相逢
星月不相逢 2020-12-06 14:57

In continuing from a previous case that was assisted by @Erwin Brandstetter and @Craig Ringer, I have fixed my code to become as follows. Note, that my function myresu

2条回答
  •  醉酒成梦
    2020-12-06 15:27

    I think I found a solution too, using a refcursor.
    I would be very glad if you could go through it, check and tell me if you think it is 'Kosher'. Frankly, I am not too sure what I've came up with here, as I am not that familiar with the syntax. But I was rather able to synthesize this using different examples I found on the web. It seems to work for me. I would be very glad if you could articulate this solution for me and for other users - and tell what do you think of it.

    First lets create the function that constructs the dynamic SELECT statement:

    CREATE OR REPLACE FUNCTION myresult2()
      RETURNS text AS 
    $func$
    DECLARE
       myoneliner text;
       mytable    text := 'dkj_p_k27ac';
       myprefix   text := 'enri';
    BEGIN
       SELECT INTO myoneliner  
              'SELECT '
            || string_agg(quote_ident(column_name::text), ',' ORDER BY column_name)
            || ' FROM ' || quote_ident(mytable)
       FROM   information_schema.columns
       WHERE  table_name = mytable
       AND    column_name LIKE myprefix||'%'
       AND    table_schema = 'public';  -- schema name; might be another param
    
       -- RAISE NOTICE 'My additional text: %', myoneliner; -- for debugging
       RETURN myoneliner;
    END
    $func$ LANGUAGE plpgsql;
    

    Now, lets create a second function that can execute the string TEXT output of the first function myresult2():

    CREATE OR REPLACE FUNCTION show_mytable(ref refcursor)
      RETURNS refcursor AS
    $func$
    DECLARE
       mydynamicstatment text := myresult2();
    BEGIN       
       OPEN ref FOR EXECUTE mydynamicstatment;
       RETURN ref;  -- return cursor to the caller
    END;
    $func$ LANGUAGE plpgsql;
    

    Call:

    BEGIN;
    SELECT show_mytable('roy');
    FETCH ALL IN "roy";
    

提交回复
热议问题