【问题标题】:postgresql - customized output file with comma separated columnspostgresql - 带有逗号分隔列的自定义输出文件
【发布时间】:2016-04-21 04:30:38
【问题描述】:

我们使用的是 postgresql 8/psql 8.4 版。我正在查询 information_schema.columns 的列名,并想生成一个文本文件/输出文件,所以:

UNLOAD ('select 
col1,
col2,
col3,
col4,
col5)
to more text here

UNLOAD ( 'select col1,col2,col3,col4,col5) to more text here

所以,我基本上希望输出 colname 后跟 "," - colname,

这可能吗?感谢您的帮助。

【问题讨论】:

    标签: postgresql plpgsql psql


    【解决方案1】:

    这将创建一个这样的字符串:

    SELECT  'UNLOAD ( ''select ' ||
            array_to_string(array_agg(column_name::text), ',') ||
            ' to more text here'
    FROM    information_schema.columns
    WHERE   table_schema = 'public'
    AND     table_name = 'whatever'
    ;
    

    您可以使用\o 将其发送到文件,或使用COPY (...) TO STDOUT

    【讨论】:

    • 另一件事。如果我需要添加带引号的字符串怎么办? ' to more 'text' here'
    • 如果你在一个单引号字符串中将两个单引号并排放置,那将在你的字符串中给你一个单引号。您可以按照'UNLOAD ( ''select '中的示例进行操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多