在 postgresql 的子查询中使用执行

Using execute in subquery in postgresql

我正在我的函数中创建一个动态查询,我需要从中提取数据。 现在我想执行那个查询。

像这样:

declare
df_id varchar;
BEGIN
/*creating dynamic query in run time and saving it in df_id in string format
say df_id='select col from schema.table_name**'*/
CREATE TEMP TABLE temp_table ON COMMIT DROP AS
    execute df_id;

我该怎么做? 另外,有没有其他方法可以在字符串变量中执行查询并将其存储到临时 table?

您需要在动态 SQL 中包含 CREATE TABLE

假设变量df_id已经包含了SELECT语句,你可以这样做:

df_id := 'CREATE TEMP TABLE temp_table ON COMMIT DROP AS '||df_id;
execute df_id;