背景:我正在写我的第一篇文章pgTAP http://pgtap.orgPL/pgSQL 函数的测试用例,并从小处开始使用 psql 测试脚本。没有问题,但我遇到了一个小烦恼psql变量 http://www.postgresql.org/docs/current/static/app-psql.html#APP-PSQL-VARIABLES.
在我的测试脚本中,我首先将大量测试数据转储到相关表中,然后使用由序列生成的主键引用数据。我发现能够创建一个包含主键的变量很方便。这就是我正在寻找的:
scalasb=> \set the_id (select currval('id_data_id_seq'))
scalasb=> \echo :the_id
54754
scalasb=>
但这就是我得到的:
scalasb=> \set the_id (select currval('id_data_id_seq'))
scalasb=> \echo :the_id
(selectcurrval('id_data_id_seq'))
scalasb=>
我有一个解决方法(请参阅下面的示例),但看起来 psql 变量不是适合这项工作的工具。或者它们只是与我在 Oracle sqlplus 中使用的不同绑定变量 http://www.adp-gmbh.ch/ora/sqlplus/use_vars.html ...
所以我的问题是:如何将 SQL 查询的返回值绑定到 psql 脚本中的变量中?
我正在使用 9.1 的 linux。
-- this is a simplified example to illustrate the problem
begin;
create table id_data(id serial primary key, data text not null);
create or replace function get_text(p_id bigint)
returns text
as $$
declare
v_data constant text := data from id_data where id = p_id;
begin
return v_data;
end;
$$ language plpgsql;
insert into id_data(data) values('lorem ipsum');
-- this works correctly but is a rather verbose (especially when one have
-- more of these, in the same query/function)
select get_text((select currval('id_data_id_seq')));
-- instead I'd like to set the id to a variable and use that but this
-- seems to be impossible with psql, right ?
\set the_id (select currval('id_data_id_seq'))
\echo First try: :the_id
--select get_text(:the_id); -- this will fail
-- this works and reveals psql variables' true nature - they are just a
-- textual replacements
\set the_id '(select currval(\'id_data_id_seq\'))'
\echo Second try: :the_id
select get_text(:the_id);
rollback;
恐怕你做不到 - 我为 psql 编写了一些补丁,但它不在核心中
您可以使用解决方法:
postgres=# \set myvar `psql -A -t -c "select version()" postgres `
postgres=# \echo :myvar
PostgreSQL 9.1.4 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.7.0 20120507 (Red Hat 4.7.0-5), 64-bit
Note:PostgreSQL 9.3 (2013) 及更新版本的支持\gset
命令。使用此命令,上述解决方法是毫无根据的:
(2023-04-02 17:03:00) postgres=# select version() as myvar \gset
(2023-04-02 17:03:06) postgres=# \echo :myvar
PostgreSQL 16devel on x86_64-pc-linux-gnu, compiled by gcc (GCC) 13.0.1 20230318 (Red Hat 13.0.1-0), 64-bit
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)