我试图在下面的示例中使用变量运行 PSQL 脚本,而无需声明函数并且必须调用它们。
DECLARE
result TEXT;
BEGIN
SELECT INTO result name
FROM test;
RAISE NOTICE result;
END;
其中表test
只有 1 行和列。这是否可能无需将此脚本包装在函数中。这将使我可以更轻松地通过命令行调用脚本。
多谢你们。
我试图在下面的示例中使用变量运行 PSQL 脚本,而无需声明函数并且必须调用它们。
DECLARE
result TEXT;
BEGIN
SELECT INTO result name
FROM test;
RAISE NOTICE result;
END;
其中表test
只有 1 行和列。这是否可能无需将此脚本包装在函数中。这将使我可以更轻松地通过命令行调用脚本。
多谢你们。
You can use DO
to create and execute an anonymous function:
DO
executes an anonymous code block, or in other words a transient anonymous function in a procedural language.
Something like this:
do $$
declare result text;
begin
select name into result from test;
raise notice '%', result;
end;
$$;
I also fixed your raise notice
.
If you just want to dump the single value from the table to the standard output in a minimal format (i.e. easy to parse), then perhaps --tuples-only
will help:
-t
--tuples-only
Turn off printing of column names and result row count footers, etc. This is equivalent to the\t
command.
So you could say things like this from the shell:
result=$(echo 'select name from test;' | psql -t ...)