--下面是返回一个ROW类型的例子,可以用RECORD类型和%ROWTYPE类型来付值

CREATE table ret_row
(
    bh varchar(10),
    xm varchar(20),
    xb VARCHAR(2)
) ;

INSERT INTO ret_row VALUES('001','阿弟','男');
INSERT INTO ret_row VALUES('002','吕不为','男');
INSERT INTO ret_row VALUES('003','有理想的猪','男');

CREATE OR REPLACE FUNCTION ret_row() RETURNS SETOF ret_row AS 
$$
DECLARE
     v_rec ret_row%rowtype;
     v_rec_record RECORD;
BEGIN
     FOR v_rec IN select * from ret_row LOOP
         RETURN NEXT v_rec;
     END LOOP;     
     FOR v_rec_record IN select * from ret_row LOOP
         RETURN NEXT v_rec_record;
     END LOOP;                                 
     RETURN ;
END;
$$
LANGUAGE PLPGSQL;

SELECT * FROM ret_row();


--下面是用自定义TYPE返回一个RECORD,可以用RECORD类型和%ROWTYPE类型来付值
CREATE TYPE ret_type AS
(
   bh VARCHAR,
   xm VARCHAR   
);

CREATE OR REPLACE FUNCTION ret_type() RETURNS SETOF ret_type AS 
$$
DECLARE
     v_rec ret_type;
     v_rec_record RECORD;
BEGIN
     FOR v_rec IN SELECT bh,xm FROM ret_row LOOP
         RETURN NEXT v_rec;
     END LOOP;
     FOR v_rec_record IN SELECT bh,xm FROM ret_row LOOP
         RETURN NEXT v_rec_record;
     END LOOP;              
     RETURN ;
END;
$$
LANGUAGE PLPGSQL;

SELECT * FROM ret_type()


--得用OUT返回
CREATE OR REPLACE FUNCTION ret_out(OUT a_bh varchar,OUT a_xm VARCHAR) RETURNS SETOF RECORD AS
$$
DECLARE
    v_rec_record RECORD;
BEGIN
    FOR v_rec_record IN SELECT bh,xm FROM ret_row LOOP
        a_bh:=v_rec_record.bh;
        a_xm:=v_rec_record.xm;  
        RETURN NEXT;
    END LOOP; 
END;
$$
LANGUAGE PLPGSQL;

SELECT * FROM ret_out();


还有种是在查询结果集后面指定列名
CREATE OR REPLACE FUNCTION ret_record() RETURNS SETOF RECORD AS
$$
DECLARE
    v_rec RECORD;
BEGIN
    FOR v_rec IN SELECT bh,xm FROM ret_row LOOP
        RETURN NEXT v_rec;
    END LOOP;             
    RETURN;
END;
$$
LANGUAGE PLPGSQL;

SELECT * FROM ret_record() t(bh VARCHAR,xm VARCHAR);


引用 http://bbs.pgsqldb.com/client/post_show.php?zt_auto_bh=53950 这都是在当前明确返回的结果内容的前提下 对于绝大部分的应用来说 是ok的 有一部分是需要动态返回结果 这时候需要使用游标 或者说 动态返回的结果集是可以预知的 可以采用第二种方式 一般情况下 使用OUT 使用更方便