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

落爺英雄遲暮 提交于 2019-12-02 07:37:45

问题


In continuation to a previous case, in which a dynamic SELECT query that uses refcursor was created and then was executed - I would like to ask the following: The desired output that we got from the indicated procedure was output into the DataOutput. I would like to find a way to store the data into a new table in the db.

Instead of the straight forward command:

CREATE TABLE mydaughtertable AS
SELECT enrich_d_dkj_p_k27ac,enrich_lr_dkj_p_k27ac,enrich_r_dkj_p_k27ac
FROM dkj_p_k27ac

The idea is to run something like:

CREATE TABLE mydaughtertable AS myresult('dkj_p_k27ac','enri') 

But this scripting is incorrect and gives the following error:

ERROR:  syntax error at or near "myresult"
LINE 1: CREATE TABLE mydaughtertable AS myresult('dkj_p_k27ac','enri...
                                        ^
********** Error **********

ERROR: syntax error at or near "myresult"
SQL state: 42601
Character: 33

回答1:


This is solved more easily than your previous question, because we don't get in trouble with dynamic return types here. You just need to concatenate the query string correctly before passing it to EXECUTE.

For a new table:

DO
$$
BEGIN
EXECUTE 'CREATE TABLE mydaughtertable AS ' || myresult('dkj_p_k27ac','enri');
END
$$;

Where myresult(...) returns the text for a valid SELECT statement.

To add to an existing table:

...
EXECUTE 'INSERT INTO TABLE mydaughtertable(<colum list>) '
      || myresult('dkj_p_k27ac','enri');
...

If you know the result type of the query matches the table, you can omit the list of target columns.



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

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