如果我正确理解您的要求:
从函数中返回一行或不返回,并允许对返回的行(如果有)执行更多操作。
测试表:
CREATE TABLE emptytable(id int, txt text); -- multiple columns
返回一个或不返回一个完整的表格行:
CREATE OR REPLACE FUNCTION selectany_all()
RETURNS SETOF emptytable AS
$func$
DECLARE
_out emptytable;
BEGIN
FOR _out IN
SELECT * FROM emptytable LIMIT 1
LOOP
-- do something with _out before returning
RAISE NOTICE 'before: %', _out;
RETURN NEXT _out;
-- or do something with _out after returning row
RAISE NOTICE 'after: %', _out;
END LOOP;
END
$func$ LANGUAGE plpgsql;
对于更灵活的方法:返回任意列:
CREATE OR REPLACE FUNCTION selectany_any()
RETURNS TABLE (id int, txt text) AS
$func$
BEGIN
FOR id, txt IN
SELECT e.id, e.txt FROM emptytable e LIMIT 1
LOOP
-- do something with id and text before returning
RAISE NOTICE 'before: %, %', id, txt;
RETURN NEXT;
-- or do something with id and text after returning row
RAISE NOTICE 'after: %, %', id, txt;
END LOOP;
END
$func$ LANGUAGE plpgsql;
注意,如果没有行,LOOP永远不会输入。因此,您不会从我的测试代码中得到NOTICE。
这两个函数也适用于返回的 n 行,LIMIT 1 仅适用于此特定请求。
密切相关,有更多解释: