--如下两个表
table1
idx      code     name
1        A1       第一次考试
2        A2       第二次考试
3        A3       第三次考试
4        QZ       期中考试
……table2
xh      name       scores
1       张飞       {1,3,0,2}
2       吕布       {2,1,2,1}
3       孔明       {5,5,5,5}--需要的结果
--查询table2.xh=1得到如下结果
idx     code      table1_name     score
----------------------------------------
1       A1        第一次考试      1
2       A2        第二次考试      3
3       A3        第三次考试      0
4       A4        期中考试        2--table2.scores是integer[]类型
--table1.idx 对应table2.scores的数组索引号
--必须要用函数返回一个指针
--我写的如下,但不能工作
--我完全不得PL/pgSQL的要领,所以写的很难看,希望多多指点
CREATE OR REPLACE FUNCTION get_scores (_xh integer)
  RETURNS refcursor AS
$BODY$
DECLARE
    t1 RECORD;
    recs RECORD;
    rs refcursor;
BEGIN
FOR t1 IN SELECT * FROM table1 LOOP
    SELECT INTO recs
        t1.idx AS "idx",
        t1.code AS "code", 
        t1.name[1] AS "table1_name",
        table2.scores[t1.idx] AS "score"
    FROM table2 
    WHERE table2.xh=_xh;
    --FETCH recs INTO rs;
END LOOP;
OPEN rs FOR SELECT recs;
RETURN rs;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

解决方案 »

  1.   

    FOR t1 IN SELECT * FROM table1 LOOP 
        SELECT INTO recs 
            t1.idx AS "idx", 
            t1.code AS "code", 
            t1.name[1] AS "table1_name", 
            table2.scores[t1.idx] AS "score" 
        FROM table2 
        WHERE table2.xh=_xh; 
        return recs next;
        -- 好象是, 再看看文档
    END LOOP; 
      

  2.   

    如何把record转换成refcursor呢?
      

  3.   

    不能将record转化为refcusor, 而且record表示的只是一行记录, 你的原义是记录集.你要么
    将你上面for ...end loop 写成一条select ...sql语句
     然后 open rs for select ...也可以
    将你上面for ...end loop 建成一个临时表
     然后 open rs for select * from 临时表       
      

  4.   

    我倒是想写成一条select语句但不知道要如何写。
      

  5.   

    SELECT a.scores[1],t.idx,t.name from tab1 t,tab2 a where a.xh=1 and a.scores[1] = t.idx;只要把 a.scores[1] 中的 值改改就行了
      

  6.   


    你这写法是错的,关系错了。a.scores[1] 不等于 t.idx
    他们之间的关系是: table2.scores[table1.idx] 
    table1.idx是table2.scores数组的索引号,而不是内容。
    就是说:table2.scores[1]得到的是第一次考试成绩