背景:我正在为PL / pgSQL函数编写我的第一个pgTAP测试用例,并从psql测试脚本开始。没问题,但我在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 bind variables ...
中使用的不同所以我的问题:如何将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;
答案 0 :(得分:5)
我害怕你不能这样做 - 我为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