返回1行的setof记录

时间:2014-04-28 18:37:26

标签: sql postgresql plpgsql

我正在改变PLPGSQL功能,我遇到了一个小问题。首先让我发布它的声明:

CREATE OR REPLACE FUNCTION permissions(_principal text)
  RETURNS SETOF record AS
$BODY$
DECLARE
    id integer := 0;
    rolerow record ;

在这个函数中,有一些情况由IF语句控制,并且在所有这些语句中,返回值是多个查询的UNION,例如:

FOR rolerow IN (
    (SELECT 'role1' AS role FROM table1 WHERE id = table1.id)
    UNION (SELECT 'role2' AS role FROM table2 WHERE id = table2.id)
    UNION (SELECT 'role3' AS role FROM table3 WHERE id = table3.id)
    ) 
LOOP
    RETURN NEXT rolerow;
END LOOP;
RETURN;

一切正常,但在一种情况下,我需要返回一个查询结果,即SETOF record,但只有一项,所以我这样做:

FOR rolerow IN (
    SELECT 'role4' AS role FROM table4 WHERE id = table4.id
) 
LOOP
    RETURN NEXT rolerow;
END LOOP;
RETURN;

我也试过

RETURN QUERY SELECT 'role4' AS role FROM table4 WHERE id = table4.id;

但在这两种情况下,我都会得到与回复相同的错误:

ERROR:  structure of query does not match function result type
DETAIL:  Returned type unknown does not match expected type text in column 1.

有谁知道如何解决这个问题?

如果这还不够,我会提供额外的信息。

1 个答案:

答案 0 :(得分:2)

您需要对字符串文字'role4'进行显式强制转换,而类型(类型为“未知”),与您的预期不同:

 SELECT 'role4'::text AS role FROM  ...

通常,对于简单的示例,循环更昂贵。像你已经测试过的那样使用RETURN QUERY