如何从存储在表中的字符串中准备和执行查询

时间:2019-02-07 07:15:20

标签: postgresql triggers plpgsql

此存储的函数返回查询:

DROP FUNCTION IF EXISTS get_query (
  ctl text, scm text, tbl text, seq text);
CREATE OR REPLACE FUNCTION get_query (
  ctl text, scm text, tbl text, seq text)
RETURNS text
AS
$$
    select concat('insert into ',$2,'.',$1, ' select nextval("',$4,'") as id, ',
           string_agg(concat('NEW.', column_name), ', '), ', current_timestamp as audited_at;')
    from information_schema.columns
    where table_catalog = $1
      and table_schema = $2
      and table_name = $3
$$
LANGUAGE sql;

如何PREPARE该函数返回的查询。

我想在触发触发器时在表中插入一条记录,但是我不想指定要插入的列的列表。模式可能会不断变化。因此,尝试使用准备好的语句。

此示例代码说明了我的意思是要执行的查询字符串:

DROP FUNCTION IF EXISTS fn_name (store_temporary_query text);
CREATE OR REPLACE FUNCTION fn_name (store_temporary_query text)
RETURNS table (query text)
LANGUAGE plpgsql
AS
$$
    begin

        select 'select 1 as ID' into store_temporary_query;
        return query (select store_temporary_query);

    end;
$$

select fn_name('');

上面的查询给出以下输出

fn_name
select 1 as ID

所需的结果是查询

ID
1

编辑#2

DROP FUNCTION IF EXISTS fn_name (store_temporary_query text);
CREATE OR REPLACE FUNCTION fn_name (store_temporary_query text)
RETURNS table (query text)
LANGUAGE plpgsql
AS
$$
    begin

        select 'select 1 as ID;' into store_temporary_query;
        return query execute store_temporary_query;

    end;
$$

select fn_name('');

这使我们来到这里,

Error executing SQL statement. ERROR: syntax error at or near "select"
  Position: 254 - Connection: Aurora Legacy: 794ms

1 个答案:

答案 0 :(得分:0)

您需要EXECUTE来执行存储在字符串中的查询:

RETURN QUERY EXECUTE store_temporary_query;