RETURN在函数返回集中不能有参数;在" QUERY"或其附近使用RETURN NEXT Postgres的

时间:2015-01-15 17:06:54

标签: postgresql postgresql-8.4

当我尝试编译这个函数时:

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。

1 个答案:

答案 0 :(得分:3)

除了一个拼写错误(你重复了select,并且你没有用分号终止RETURN语句),我认为你非常接近 - 只需要消除内容中的表列的歧义通过使用表名限定它们来进行查询。试试这个(希望重新格式化以提高可读性):

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中对此进行了测试,所以尚未在您的版本中测试过(我不再支持,我可能会添加)。如果您的版本和9.4之间存在关于PLPGSQL实现的问题,您可以尝试使用此表单作为替代方案:

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)