[英]How to assign result of table function to variable in PL/pgSQL
假設我有以下 function 聲明:
CREATE OR REPLACE FUNCTION build_org_branch(IN p_org_id organization.org_id%type,
IN p_padding text)
RETURNS table
(
object_id int,
parent_id int,
name text
)
然后我想用參數調用build_org_branch
並將其分配給另一個 function 內部的變量,如下所示:
declare
l_table record[]; --??????
begin
l_table := build_org_branch(1, ' '); -- is it okay?
if l_table is not null then
-- do stuff with table rows
end if;
end;
或者我應該使用其他方法來傳遞行表?
Postgres 不支持表的變量。 如果您可以傳遞一些關系內容,那么a)您可以使用臨時表或b)您可以傳遞一個復合值數組:
CREATE TYPE branch_type AS
(
object_id int,
parent_id int,
name text
)
CREATE OR REPLACE FUNCTION build_org_branch(IN p_org_id organization.org_id%type,
IN p_padding text)
RETURNS branch_type[] AS ...
然后你可以寫
declare
l_table branch_type[];
begin
l_table := build_org_branch(1, ' ');
if l_table is not null then
-- do stuff with table rows
end if;
end;
這是數組到數組的賦值。 表格到數組也是可能的,但始終必須是 static 類型。
CREATE OR REPLACE FUNCTION build_org_branch(IN p_org_id organization.org_id%type,
IN p_padding text)
RETURNS SETOF branch_type AS ...
和處理:
declare
l_table branch_type[];
begin
l_table := ARRAY(SELECT build_org_branch(1, ' '));
if l_table is not null then
-- do stuff with table rows
end if;
end;
對於較少的行數(至一萬行),應首選 arrays。 對於大量行,您應該使用臨時表。
您已經構建了一個返回表的 function,因此以這種方式處理結果。
do $$
declare
rec record;
begin
for rec in (select * from build_org_branch(101, ''))
loop
raise notice 'Returned Row: object_id=>%, name=>%, parent_id=>%'
, rec.object_id
, rec.name
, rec.parent_id ;
-- do stuff with table rows
end loop;
end;
$$;
我沒有你的表,所以我會對一些值進行硬編碼,但它們的填充方式不是問題,而是你之后要做的事情。 見小提琴。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.