如何编写postgresql脚本将数据从表导出到csv文件

如何编写postgresql脚本将数据从表导出到csv文件,postgresql,Postgresql,我只想编写一个脚本,在特定的postgresql数据中查找表,并将整个数据转换/导出为单个csv文件 帮助我从postgresql中的示例脚本开始您可以通过查询信息获取表。\u schema.tables视图: dwh=> \d information_schema.tables View "information_schema.tables" Column | Typ

我只想编写一个脚本,在特定的postgresql数据中查找表,并将整个数据转换/导出为单个csv文件


帮助我从postgresql中的示例脚本开始

您可以通过查询信息获取表。\u schema.tables视图:

dwh=> \d information_schema.tables 
                       View "information_schema.tables"
            Column            |               Type                | Modifiers 
------------------------------+-----------------------------------+-----------
 table_catalog                | information_schema.sql_identifier | 
 table_schema                 | information_schema.sql_identifier | 
 table_name                   | information_schema.sql_identifier | 
 table_type                   | information_schema.character_data | 
 self_referencing_column_name | information_schema.sql_identifier | 
 reference_generation         | information_schema.character_data | 
 user_defined_type_catalog    | information_schema.sql_identifier | 
 user_defined_type_schema     | information_schema.sql_identifier | 
 user_defined_type_name       | information_schema.sql_identifier | 
 is_insertable_into           | information_schema.character_data | 
 is_typed                     | information_schema.character_data | 
 commit_action                | information_schema.character_data | 
对于列也有一个类似的视图:information_schema.columns。此外,psql有选项-E,它显示隐藏的查询,即由诸如“\d”

Postgres有COPY命令(http://www.postgresql.org/docs/8.4/interactive/sql-copy.html)但您必须是数据库超级用户(postgres)才能将其用于文件(您可以使用COPY…to STDOUT HEADER CSV)

快速脏shell脚本(&D):

psql ... -A -t -U dwh -c "select '\\\copy ' || table_name || ' to ''' || table_name || '.csv'' csv header' from information_schema.tables" | psql ...
您必须用连接参数替换“…”

可能重复的