从网上找到例子:
可以说,RETURN NEXT要用在循环中:
例子一:
数据准备:
CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT); INSERT INTO foo VALUES (1, 2, 'three'); INSERT INTO foo VALUES (4, 5, 'six');
生成函数:
CREATE OR REPLACE FUNCTION getAllFoo() RETURNS SETOF foo AS $BODY$ DECLARE r foo%rowtype; BEGIN FOR r IN SELECT * FROM foo WHERE fooid > 0 LOOP -- can do some processing here RETURN NEXT r; -- return next row of SELECT END LOOP; RETURN; END $BODY$ LANGUAGE 'plpgsql';
运行结果:
pgsql=# SELECT * FROM getallfoo(); fooid | foosubid | fooname -------+----------+--------- 1 | 2 | three 4 | 5 | six (2 rows) pgsql=#
例子二:
数据准备:
CREATE TABLE test (textcol varchar(10), intcol int); INSERT INTO test VALUES ('a', 1); INSERT INTO test VALUES ('a', 2); INSERT INTO test VALUES ('b', 5); INSERT INTO test VALUES ('b', 6);
生成函数:
CREATE OR REPLACE FUNCTION ReturnNexting(pText Text) RETURNS SETOF test AS $$ DECLARE rec RECORD; BEGIN FOR rec IN SELECT * FROM test WHERE textcol = pText LOOP RETURN NEXT rec; END LOOP; RETURN; END; $$ LANGUAGE plpgsql;
运行结果:
pgsql=# SELECT * FROM ReturnNexting('a'); textcol | intcol ---------+-------- a | 1 a | 2 (2 rows) pgsql=#