Postgres Copy from Variable with CSV data

感情迁移 提交于 2019-11-29 15:41:46

That's not possible with the SQL COPY command. COPY only copies from a file or STDIN.

You can either write the content of the variable to a file or pipe it via STDIN. Only makes sense for more than a couple of rows.


I think I misunderstood your question before the update, you probably don't need this:

The file path can not be exchanged like other data items, and you can't use a prepared statement for that. Build the whole statement before executing or resort to dynamic SQL with a server-side function like:

CREATE OR REPLACE FUNCTION f_cp(_file text)
  RETURNS void AS
$BODY$
BEGIN
EXECUTE format($$COPY zip_codes FROM %L DELIMITER ',' CSV$$, $1);
END
$BODY$
  LANGUAGE plpgsql;

Call:

SELECT f_cp('/var/lib/postgres/sync/myfile.csv')

format() requires Postgres 9.1 or later.

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