简体   繁体   English

如何在同一个文件中的psql复制中使用sql命令

[英]How to use sql commands with psql copy in the same file

I have a series to sql commands that I'm running, and one of them is a copy of the sql results to a file. 我有一系列要运行的sql命令,其中一个是将sql结果复制到文件中。 I then want to drop the table. 然后,我想放桌子。 Here's an example: 这是一个例子:

psql - d dw -U postgres -f input.sql

contents of input.sql --------- input.sql的内容---------

CREATE TABLE a_temp AS
SELECT a.*
    FROM a

COPY dw.a_temp to '/opt/data/a/a.csv (delimiter E'\x01');

DROP table a_temp;

Is this all possible to do in one file? 这一切都可以在一个文件中完成吗? Right now the script just stops after the CREATE TABLE, and the copy is never run. 现在,该脚本仅在CREATE TABLE之后停止,并且该副本永远不会运行。 We're trying to avoid multiple invocation of the PSQL executable. 我们试图避免多次调用PSQL可执行文件。

Missing semicolon after CREATE TABLE and missing apostrophe after path. CREATE TABLE之后缺少分号,而path之后缺少撇号。

CREATE TABLE a_temp AS
SELECT * FROM a;

COPY dw.a_temp TO '/opt/data/a/a.csv' DELIMITER E'\x01';

DROP table a_temp;

Depending on context there can be also problem with schema. 根据上下文,架构也可能存在问题。 If you set SEARCH_PATH to 'dw' it should work, otherwise you probably create table a_temp in public, and try to copy from dw. 如果将SEARCH_PATH设置为'dw',它应该可以工作,否则您可能会在公共环境中创建表a_temp,并尝试从dw复制。

What is your version of postgresql? 您的postgresql版本是什么? In later versions you can COPY directly from a SELECT query. 在更高版本中,您可以直接从SELECT查询复制。 – Igor Romanchenko –伊戈尔·罗曼琴科(Igor Romanchenko)

This is the solution I ultimately went with. 这是我最终选择的解决方案。 So the statement looks like 所以该语句看起来像

COPY (SELECT * FROM a)
TO '/opt/data/a/a.csv' 
WITH DELIMITER E'\x01';

No temporary table necessary! 无需临时表!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM