我想使用一个函数将查询的值分配给变量。然而,表名的名称是从我的函数中前面几行的输出中派生出来的。
ref_A int
ref_B int
...
select count(*) into ref_C from "table" || ref_B || ref_A
在本例中,表的名称是“table refA refB”
问题是语法错误。显然,我需要使用动态查询来连接名称的名称,但我不知道如何将结果分配给变量。
正如已经建议,您正在寻找
EXECUTE...INTO
:演示
create table "table21" as select n from generate_series(1,9,1) g(n);
create function my_func() returns int language plpgsql as $func$
declare
ref_A int := 1;
ref_B int := 2;
ref_C int;
your_table_name text:='table'|| ref_B || ref_A ;
begin
execute format($dyn_sql$
select count(*) from %1$I
$dyn_sql$,
your_table_name)
into ref_C;--this right here
return ref_C;
end $func$;
select * from my_func();
我的函数 |
---|
9 |