PostgreSQL PSQL SELECT 转化为一个变量

PostgreSQL PSQL SELECT into a variable

在 Postgres 控制台 (PSQL) 上,我尝试编写一个简单的 'batch' 测试:

\set oid

\set username 'john'
\set emailadr 'john@mailbox.net'
\set password 'jjjj'
INSERT INTO :oid SELECT auc_user_insert(:'username', :'emailadr', :'password');
SELECT auc_user_select(:oid);
SELECT auc_user_delete(:oid);

auc_user_insertauc_user_selectauc_user_delete 是特定于应用程序的 Postgres 函数,并且对每个自身(在查询工具中)都能正常工作。 insert 函数 returns 一个 bigint 作为唯一 id,我想将其分配给变量 oid 以便在下一行中使用。

但是在 INTO :oid 语句的 PSQL 中我得到了错误

ERROR:  Relation 'bigint' doesn't exist

出了什么问题,使用这样一个变量的正确方法是什么?感谢任何提示!

假设 INSERT INTO 是为了影响 :oid 变量而不是将 select 的结果插入 table,您需要这样:

SELECT auc_user_insert(:'username', :'emailadr', :'password') AS oid;
\gset
SELECT auc_user_select(:oid);
SELECT auc_user_delete(:oid);

\gset 是自 psql 9.3

以来的新元命令

如果您使用的是旧版本,则很难模仿它。

联机帮助页中的描述:

\gset [ prefix ]

Sends the current query input buffer to the server and stores the query's output into psql variables (see Variables). The query to be executed must return exactly one row. Each column of the row is stored into a separate variable, named the same as the column