COPY csv using custom filename path

本秂侑毒 提交于 2019-12-11 02:25:48

问题


I'm getting some issues while trying to export a query to CSV using the COPY function.

The COPY runs ok and exports the query successfully if not using custom filenames on the TO.

The issue is related to add a "datestamp" (kinda) to the filename created.

declare var1 varchar(25);
DECLARE STATEMENT TEXT;
select into var1 current_date -1;
STATEMENT := 'COPY (SELECT * from myTable) To ''E'C:\\Exports\\export_'||var1||'.csv' ''With CSV';
EXECUTE STATEMENT;

In this case, var1 gets a value like 2013-12-16 and I need to add that to the filename to obtain export_2012-12-16.csv

I'm assuming that the ' are misplaced. I've tried several combinations without success and off course the error is ERROR: syntax error at or near "C".


回答1:


plpgsql code could work like this:

...
DECLARE
   var1 text;
BEGIN
var1 := to_char(current_date - 1, 'YYYY-MM-DD');
EXECUTE $$COPY (SELECT * from myTable)
          TO E'C:\\Exports\\export_$$ || var1 || $$.csv' WITH CSV$$;
...

Your quotes got tangled. Using dollar-quoting to simplify. Note that syntax highlighting here on SO is misleading because it does not understand dollar-quoting.

DECLARE is only needed once (not an error though). Plus, BEGIN was missing.

And to_char() makes the text representation of a date independent of the locale.



来源:https://stackoverflow.com/questions/20636947/copy-csv-using-custom-filename-path

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