如何使用psql命令行远程保存多个FOR循环结果到远程客户端文件?
How to use psql command line to remotely save multiple FOR loop results to remote client files?
我有一个匿名函数,其中包含一个执行 100 次的 FOR 循环中的查询,我需要将 100 个结果集保存为远程客户端上的 100 个文件(不是在服务器上)。
似乎 psql \copy
元命令应该是执行此操作的方法,但我不知所措。也许是这种形式?
\copy (anonymous_function_w/_FOR_loop_here) to 'filename.txt'
其中 filename.txt 是在每次迭代中根据 FOR 循环变量的值构建的。这很重要 - 远程客户端上的文件需要根据 FOR 循环的变量命名。
有什么办法可以解决这个问题吗?我想另一种方法是将所有 100 个查询结果 UNION 成一个大结果,在一个字段中使用 FOR 循环的变量值,然后使用 bash 脚本将其拆分为 100 个适当命名的文件。但是我的 bash 技能很蹩脚。如果 psql 可以直接完成该工作,那就太好了。
编辑:我要补充的是 FOR 循环变量看起来像这样:
FOR rec IN SELECT DISTINCT county FROM voter.counties
因此文件名将从 rec.county + '.txt'
典型的方法是使用生成必要语句的 SQL 语句,将输出假脱机到脚本文件中,然后 运行 该文件。
类似于:
-- prepare for a "plain" output without headers or something similar
\a
\t
-- spool the output into export.sql
\o export.sql
select format('\copy (select * from some_table where county = %L) to ''%s.txt''', county, county)
from (select distinct county from voter.counties) t;
-- turn spooling off
\o
-- run the generated file
\i export.sql
因此对于 voters.counties
中的每个县名,export.sql
将包含:
\copy (select * from some_table where county = 'foobar') to 'foobar.txt'
我有一个匿名函数,其中包含一个执行 100 次的 FOR 循环中的查询,我需要将 100 个结果集保存为远程客户端上的 100 个文件(不是在服务器上)。
似乎 psql \copy
元命令应该是执行此操作的方法,但我不知所措。也许是这种形式?
\copy (anonymous_function_w/_FOR_loop_here) to 'filename.txt'
其中 filename.txt 是在每次迭代中根据 FOR 循环变量的值构建的。这很重要 - 远程客户端上的文件需要根据 FOR 循环的变量命名。
有什么办法可以解决这个问题吗?我想另一种方法是将所有 100 个查询结果 UNION 成一个大结果,在一个字段中使用 FOR 循环的变量值,然后使用 bash 脚本将其拆分为 100 个适当命名的文件。但是我的 bash 技能很蹩脚。如果 psql 可以直接完成该工作,那就太好了。
编辑:我要补充的是 FOR 循环变量看起来像这样:
FOR rec IN SELECT DISTINCT county FROM voter.counties
因此文件名将从 rec.county + '.txt'
典型的方法是使用生成必要语句的 SQL 语句,将输出假脱机到脚本文件中,然后 运行 该文件。
类似于:
-- prepare for a "plain" output without headers or something similar
\a
\t
-- spool the output into export.sql
\o export.sql
select format('\copy (select * from some_table where county = %L) to ''%s.txt''', county, county)
from (select distinct county from voter.counties) t;
-- turn spooling off
\o
-- run the generated file
\i export.sql
因此对于 voters.counties
中的每个县名,export.sql
将包含:
\copy (select * from some_table where county = 'foobar') to 'foobar.txt'