从网上找到例子:sql
能够说,RETURN NEXT要用在循环中:函数
例子一:spa
数据准备:code
CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT); INSERT INTO foo VALUES (1, 2, 'three'); INSERT INTO foo VALUES (4, 5, 'six');
生成函数:blog
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';
运行结果:three
pgsql=# SELECT * FROM getallfoo(); fooid | foosubid | fooname -------+----------+--------- 1 | 2 | three 4 | 5 | six (2 rows) pgsql=#
例子二:get
数据准备:class
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);
生成函数:test
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=#