我正在尝试让 PSQL 脚本在如下示例中使用变量运行,而无需声明函数并调用它们。
DECLARE
result TEXT;
BEGIN
SELECT INTO result name
FROM test;
RAISE NOTICE result;
END;
其中表 test
只有 1 行和 1 列。这是否可能而无需将此脚本包装在函数中。这将使我能够更轻松地通过 say 命令行调用脚本。
谢谢你们。
最佳答案
您可以使用 DO
创建和执行匿名函数:
DO
executes an anonymous code block, or in other words a transient anonymous function in a procedural language.
像这样:
do $$
declare result text;
begin
select name into result from test;
raise notice '%', result;
end;
$$;
我还修复了你的raise notice
。
如果您只是想以最小格式(即易于解析)将表中的单个值转储到标准输出,那么可能是 --tuples-only
将帮助:
-t
--tuples-only
Turn off printing of column names and result row count footers, etc. This is equivalent to the\t
command.
所以你可以在 shell 中这样说:
result=$(echo 'select name from test;' | psql -t ...)
关于postgresql - PSQL 脚本中的变量无需创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11857594/