我需要从PostgreSQL数据库的多个表中提取SQL文件.这就是我到目前为止想出来的:
pg_dump -t 'thr_*' -s dbName -U userName > /home/anik/psqlTest/db_dump.sql
但是,如您所见,所有以前缀thr
开头的表都被导出到单个统一文件(db_dump.sql
).我总共有近90个表可以从中提取SQL,因此必须将数据存储到单独的文件中.
我该怎么做呢?提前谢谢您.
我需要从PostgreSQL数据库的多个表中提取SQL文件.这就是我到目前为止想出来的:
pg_dump -t 'thr_*' -s dbName -U userName > /home/anik/psqlTest/db_dump.sql
但是,如您所见,所有以前缀thr
开头的表都被导出到单个统一文件(db_dump.sql
).我总共有近90个表可以从中提取SQL,因此必须将数据存储到单独的文件中.
我该怎么做呢?提前谢谢您.
如果您乐于硬编码表列表,但只希望每个表都位于不同的文件中,则可以使用shell脚本循环多次运行pg_dump
命令,每次循环时都替换表名:
for table in table1 table2 table3 etc;
do pg_dump -t $table -U userName dbName > /home/anik/psqlTest/db_dump_dir/$table.sql;
done;
EDIT:可以扩展此方法,通过psql运行查询并将结果反馈到循环中,而不是硬编码的列表,从而动态获取表列表:
for table in $(psql -U userName -d dbName -t -c "Select table_name From information_schema.tables Where table_type='BASE TABLE' and table_name like 'thr_%'");
do pg_dump -t $table -U userName dbName > /home/anik/psqlTest/db_dump_dir/$table.sql;
done;
在这里,psql -t -c "SQL"
运行SQL
并输出结果,没有页眉或页脚;因为只 Select 了一列,所以在$(command)
捕获的输出的每一行上都会有一个表名,并且您的shell将一次循环遍历它们.