36

我正在尝试创建一个返回 SELECTed 结果集的函数。当我像这样调用我的 postgres 函数时select * from tst_dates_func(),出现如下所示的错误:

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function "tst_dates_func" line 3 at SQL statement

********** Error **********

ERROR: query has no destination for result data
SQL state: 42601
Hint: If you want to discard the results of a SELECT, use PERFORM instead.
Context: PL/pgSQL function "tst_dates_func" line 3 at SQL statement

这是我创建的函数:

CREATE OR REPLACE FUNCTION tst_dates_func() 
    RETURNS TABLE( date_value date, date_id int, date_desc varchar) as
$BODY$   
BEGIN
    select a.date_value, a.date_id, a.date_desc from dates_tbl a;
END;
$BODY$
      LANGUAGE plpgsql;

我不确定为什么会收到上述错误。我想运行select * from tst_dates_func(); 并取回数据。如果需要,或者进一步加入结果集。这里有什么问题?

4

2 回答 2

54

像普通 SQL 一样做

CREATE OR REPLACE FUNCTION tst_dates_func() 
    RETURNS TABLE( date_value date, date_id int, date_desc varchar) as
$BODY$   
    select a.date_value, a.date_id, a.date_desc from dates_tbl a;

$BODY$
      LANGUAGE sql;

如果你真的需要 plpgsql 使用return query

CREATE OR REPLACE FUNCTION tst_dates_func() 
    RETURNS TABLE( date_value date, date_id int, date_desc varchar) as
$BODY$   
BEGIN
    perform SELECT dblink_connect('remote_db');
    return query
    select a.date_value, a.date_id, a.date_desc from dates_tbl a;

END;
$BODY$
      LANGUAGE plpgsql;
于 2013-06-06T15:26:25.087 回答
2
In PLPGSQL - use RETURN QUERY

CREATE OR REPLACE FUNCTION tst_dates_func() 
    RETURNS TABLE( date_value date, date_id int, date_desc varchar) as
$BODY$   
BEGIN
    RETURN QUERY (select a.date_value, a.date_id, a.date_desc from dates_tbl a);
END;
$BODY$
    LANGUAGE plpgsql;
于 2019-10-03T07:45:25.763 回答