sql - Postgres COPY 到 CSV

标签 sql postgresql

我正在尝试使用 pgAdminIII 中的 COPY 命令将查询导出到 csv 文件。

我正在使用这个命令:

COPY (SELECT CASE WHEN cast(click as int) = 1 THEN 1
    ELSE -1
    END
    || ' '
    || id
    || '|'
    || 'hr_' || substring(hour, 7,8)
    --|| ' dw_x' + substring(datename(dw, substring(hour,1,6) ),1,2)
    || ' |dw_' || substring(to_char(to_date(substring(hour, 1,6),'YYMMDD'), 'dy'),1,2)
    || ' |C1_' || c1
    || ' |C21_' || c21
    || ' |C22_' || substring(to_char(to_date(substring(hour, 1,6),'YYMMDD'), 'dy'),1,2) || '_' || substring(hour, 7,8)
    AS COL1    
  FROM clickthru.train limit 10)     
  TO 'C:\me\train.csv' with csv;

当我运行它时,我得到:

ERROR: could not open file "C:\me\train.csv" for writing: Permission denied
SQL state: 42501

然后我尝试在 psql 中使用以下内容:

grant all privileges on train to public

然后使用\z 查看访问权限,返回:

enter image description here

但我仍然得到同样的错误。我在 Windows 7 机器上使用 postgresql 9.4。还有其他建议吗?

最佳答案

copy 在 Postgrs server 进程的用户帐户下写入文件(这是服务器端操作)。

From the manual:

The file must be accessible by the PostgreSQL user (the user ID the server runs as) and the name must be specified from the viewpoint of the server

在 Windows 下,默认情况下这是系统的“网络帐户”。

显然该帐户对该目录没有写权限。

您有两种可能的解决方法:

  1. 更改目录的权限以允许所有人完全访问
  2. 改用客户端\copy命令(在psql中)

关于sql - Postgres COPY 到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28307053/

相关文章:

sql - INSERT 和 DELETE 在同一个事务中?

postgresql - 锁定具有外键约束的更新行

node.js - pg 池 - 使用具有超时功能的 pg 池的正确方法是什么

sql - 如何在 PostgreSQL 查询中对不同的元组进行排序

sql - 如何在一次查询中获得不同条件下的总和?

mysql - 无法在两个表之间创建关系

sql - 双左连接

SQL Server : Find out default value of a column with a query

sql - 使用语法错误更新 postgresql

postgresql - 创建手动输入值的 cte