2015-01-15 18 views
2

當我嘗試編譯此功能:我爲什麼會得到這個錯誤RETURN在函數返回集中不能有參數;使用RETURN NEXT或接近「QUERY」的Postgres

CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint) 
    RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) 
AS $$ 
    BEGIN 
     RETURN QUERY SELECT select sr_number,product_serial_number from temp_table where sr_number=sr_num 
    END; 
$$ 
LANGUAGE 'plpgsql' VOLATILE; 

RETURN在函數返回集中不能有參數;請在「QUERY」處或附近使用RETURN NEXT

我正在使用postgres版本8.4。

從一個錯字(你複製 select,而你沒有終止 RETURN語句用分號),我認爲你是相當接近

回答

3

除了 - 只需要通過與臺限定它們的歧義查詢中的表列名稱。試試這個(希望重新格式化,以提高可讀性):

CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint) 
    RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$ 
    BEGIN 
    RETURN QUERY 
     SELECT 
     temp_table.sr_number, temp_table.product_serial_number 
     from temp_table 
     where temp_table.sr_number=sr_num; 
    END; 
$$ LANGUAGE 'plpgsql' VOLATILE; 

警告:我只在PG 9.4測試這一點,所以在您的版本沒有測試它,但(這是不再支持,我可以補充)。用我用虛擬數據填充表

CREATE OR REPLACE FUNCTION test_proc4(sr_num bigint) 
    RETURNS TABLE(sr_number bigint, product_serial_number varchar(35)) AS $$ 
    BEGIN 
    FOR sr_number, product_serial_number IN 
     SELECT 
     temp_table.sr_number, temp_table.product_serial_number 
     from temp_table 
     where temp_table.sr_number=sr_num 
    LOOP 
     RETURN NEXT; 
    END LOOP; 
    RETURN; 
    END; 
$$ LANGUAGE 'plpgsql' VOLATILE; 

一個小的完整性檢查:

postgres=# select * from temp_table; 
sr_number | product_serial_number 
-----------+----------------------- 
     1 | product 1 
     2 | product 2 
     2 | another product 2 
(3 rows) 

postgres=# select * from test_proc4(1); 
sr_number | product_serial_number 
-----------+----------------------- 
     1 | product 1 
(1 row) 

postgres=# select * from test_proc4(2); 
sr_number | product_serial_number 
-----------+----------------------- 
     2 | product 2 
     2 | another product 2 
(2 rows) 
+0

它如果有關於您的版本和9.4之間PLPGSQL執行問題,你可以嘗試這種形式作爲替代給我同樣的錯誤'返回不能有函數返回集中的參數;請在「QUERY」處或其附近使用RETURN NEXT' – user2569524 2015-01-15 18:02:49

+0

@ user2569524因此,您的PG版本可能會略微不同於PLPGSQL(特別是'RETURN QUERY')的支持/實現。我在我的回答中添加了一個備用表單。 – rchang 2015-01-15 18:25:20

相關問題