2017-04-11 130 views
0

我已經嘗試了很多次以下的教程,但失敗了。 有人可以給我一些例子嗎? 這裏是我的代碼,它提示說:「錯誤:無效的類型名稱‘SETOF記錄’」如何在PostgreSQL的函數中返回查詢結果的行?

create or replace function find() returns SETOF RECORD 
as $$ 
declare A SETOF RECORD; 
begin 
    A=(
     select x,y 
     from ....... 

    ) 
    CASE WHEN EXISTS A 
    THEN returns query A 
    ELSE returns query (
     select x,y 
     from ...... 
    ) 
    END; 

end; 
$$ language plpgsql; 
+2

什麼是錯誤你得到?你究竟想要做什麼? (** [編輯] **您的問題,請不要在評論中發佈其他信息) –

回答

1

方式來聲明集返回函數,我記得的時刻:

--example 1 
create or replace function test() returns SETOF RECORD 
as $$ 
begin 
    RETURN QUERY SELECT * FROM generate_series(1,100); 
end; 
$$ language plpgsql; 
--test output 
select * from test() AS a(b integer) 

--example 2 
create or replace function test2() returns TABLE (b integer) 
as $$ 
begin 
    RETURN QUERY SELECT * FROM generate_series(1,100); 
end; 
$$ language plpgsql; 
--test output 
select * from test2() 

--example 3 
create or replace function test3() returns SETOF RECORD 
as $$ 
declare 
    r record; 
begin 
    FOR r IN SELECT * FROM generate_series(1,100) LOOP 
     RETURN NEXT r; 
    END LOOP; 
end; 
$$ language plpgsql; 
--test output 
select * from test3() AS a(b integer); 

--example 4 
create or replace function test4() returns setof record 
as $$ 
    SELECT * FROM generate_series(1,100) 
$$ language sql; 
--test output 
select * from test4() AS a(b integer); 

--example 5 
create or replace function test5() returns setof integer 
as $$ 
begin 
    RETURN QUERY SELECT * FROM generate_series(1,100); 
end; 
$$ language plpgsql; 
--test output 
select * from test5() 

--example 6 
create or replace function test6(OUT b integer, OUT c integer) RETURNS SETOF record 
as $$ 
begin 
    RETURN QUERY SELECT b.b, b.b+3 AS c FROM generate_series(1,100) AS b(b); 
end; 
$$ language plpgsql; 
--test output 
select * from test6() 
+0

謝謝。當我需要確定查詢結果是否存在時該怎麼辦?我想要做的是當它存在時返回它,否則返回另一個查詢的結果。 – Chen

+0

根據查詢情況,可能是'FULL JOIN','UNION'或'DISTINCT ON'。我認爲它與函數聲明沒有任何關係。您__ can't__不能將'SETOF RECORD'存儲在變量中。 –