[英]plpgsql, how to store variable into file
I want create a custom variable (string) that contain data from different tables. 我想创建一个自定义变量(字符串),其中包含来自不同表的数据。 I can't do it in one query (special order to store, and dynamic columns). 我无法在一个查询(存储的特殊顺序和动态列)中做到这一点。
Is there a way to store the variable into file? 有没有一种方法可以将变量存储到文件中?
Or using command line to save the result of one variable into file? 还是使用命令行将一个变量的结果保存到文件中?
Because of tag plpgsql
I assume that you are executing some queries inside a plpgsql function and the result saved in a variable should be send to a file. 由于存在标签plpgsql
我假设您正在plpgsql函数内执行某些查询,并且保存在变量中的结果应发送到文件中。
In plain SQL you can save a text in a file using a copy
command, something like this: 在普通SQL中,您可以使用copy
命令将文本保存在文件中,如下所示:
copy (select 'some text') to 'c:\data\sample.txt';
In a plpgsql function you should use execute
command to select a value of a variable, example: 在plpgsql函数中,应使用execute
命令选择变量的值,例如:
create or replace function copy_some_text_to_file(filename text)
returns void language plpgsql
as $$
declare
var text:= 'some text';
begin
execute format($fmt$
copy (select '%s') to '%s'
$fmt$, var, filename);
end $$;
select copy_some_text_to_file('c:\data\sample.txt')
If you want to save to file a variable with multiline string, you can use regexp_split_to_table()
: 如果要使用多行字符串将变量保存到文件,可以使用regexp_split_to_table()
:
create or replace function copy_some_text_to_file(filename text)
returns void language plpgsql
as $$
declare
var text:= 'first line\nsecond line\nthird line';
begin
execute format($fmt$
copy (select regexp_split_to_table(e'%s', e'\n')) to '%s'
$fmt$, var, filename);
end $$;
Note, that the string cannot contain a single quotation mark, which must be properly escaped. 请注意,字符串不能包含单引号,必须将其正确转义。 While in the first version you can replace '%s'
with %L
(as Erwin suggested), you cannot do that in the second version. 在第一个版本中,您可以用%L
替换'%s'
(如Erwin建议),而在第二个版本中,您不能这样做。
Read more: 阅读更多:
Executing SQL from the Linux shell you can easily redirect the result to a file: 从Linux Shell执行SQL,您可以轻松地将结果重定向到文件:
postgres@db:~$ psql mydb --tuples-only -c 'select 1' > /path/to/myfile.txt
Or execute SQL for a file: 或对文件执行SQL:
postgres@db:~$ psql mydb -t -f /path/to/myscript.sql > /path/to/myfile.txt
Or from within psql: 或从psql内部:
\o /path/to/myfile.txt
\t
SELECT 1;
\o
Everything is explained in the manual for psql . 有关所有内容,请参见psql手册 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.