Saving the output of a dynamic query that uses prepare statement into a table

时光怂恿深爱的人放手 提交于 2019-12-14 03:04:25

问题


In continuation to a previous case (a solution by @Erwin Brandstetter), in which a dynamic SELECT query that uses a 'prepare' statement was created and then was executed by calling it, as below:

--the function for making the prepare statement:

CREATE OR REPLACE FUNCTION f_prep_query (_tbl regclass, _prefix text)
  RETURNS void AS 
$func$
DECLARE
  _prep_qry text := (
     SELECT 'PREPARE stmt_dyn AS SELECT '
         || string_agg(quote_ident(attname), ',' ORDER BY attname)
         || ' FROM ' || _tbl
      FROM   pg_attribute
      WHERE  attrelid = _tbl
      AND    attname LIKE _prefix || '%'
      AND    attnum > 0
      AND    NOT attisdropped
     );
BEGIN
   EXECUTE _prep_qry;
EXCEPTION WHEN duplicate_prepared_statement THEN
   DEALLOCATE stmt_dyn;
   EXECUTE _prep_qry;
END
$func$  LANGUAGE plpgsql;

--the calling:

BEGIN; -- optional
SELECT f_prep_query('dkj_p_k27ac'::regclass, 'enri'::text);
EXECUTE stmt_dyn;

I would like to ask the following: The desired output that we get from the indicated procedure is outputted into the DataOutput. I would like to find a way to store the data into a new table in the db.


回答1:


Generally, if you just want to write to a table, don't use a prepared SELECT statement (or a cursor). That's very inefficient for the purpose.

Write to the table directly like explained in the previous answer:

  • Saving the output of a dynamic query that uses refcursor into a table

The complete INSERT could be the prepared statement. But not CREATE TABLE AS. Per documentation:

Any SELECT, INSERT, UPDATE, DELETE, or VALUES statement.



来源:https://stackoverflow.com/questions/27845824/saving-the-output-of-a-dynamic-query-that-uses-prepare-statement-into-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!