在 PSQL 控制台导出文件中可以在文件名末尾加上当前日期吗? 导出文件的名称应该像这样 table_20140710.csv 是否可以动态执行此操作? - 日期的格式可以与上面的不同,这不是很重要。
这是我的意思的例子:
\set curdate current_date
\copy (SELECT * FROM table) To 'C:/users/user/desktop/table_ ' || :curdate || '.csv' WITH DELIMITER AS ';' CSV HEADER
最佳答案
\copy
元命令不扩展变量的异常(exception)是(同时)documented
Unlike most other meta-commands, the entire remainder of the line is always taken to be the arguments of \copy, and neither variable interpolation nor backquote expansion are performed in the arguments.
要解决此问题,您可以分多个步骤构建、存储和执行命令(类似于 Clodoaldo Neto 给出的解决方案):
\set filename 'my fancy dynamic name'
\set command '\\copy (SELECT * FROM generate_series(1, 5)) to ' :'filename'
:command
有了这个,您需要在嵌入式元命令中加倍(转义)\
。请记住 \set
将所有其他参数连接到第二个参数,因此在参数之间引用空格。您可以使用 \echo :command
在执行前显示命令 (:command
)。
作为本地 \set
命令的替代方法,您还可以使用 SQL 构建命令服务器端(最佳方式取决于动态内容的来源):
SELECT '\copy (SELECT * FROM generate_series(1, 5)) to ''' || :'filename' || '''' AS command \gset
关于postgresql - psql\copy 中的变量替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24671177/