0

我有一个问题,我有一个查询,它有多个表,我想创建一个函数,将该查询作为表返回给我

SELECT mat.codigo as codmatr, mat.codigoalumno as codal, mat.codigoempresa as codemp ,mat.codigopresentacion as codpre,
    mat.codigosecretaria as codsec, mat.fecha as fechamat, mat.estado as estadomat,
    mat.vigencia as vigmat, p.apellidos as apeAl, p.apellidos||' '||p.nombres as nombrecompleto,
    p.nombres as nomAl,razonsocial ,pre.codigocurso as codcur,cur.nombre as curso
    FROM matricula mat join alumno al on mat.codigoalumno = al.codigoalumno
    join persona p on  al.codigoalumno = p.codigo
    join persona pe on mat.codigoalumno = pe.codigo
    left join empresa emp on mat.codigoempresa = emp.codigo
    join presentacion pre on mat.codigopresentacion = pre.codigo
    join curso cur on cur.codigo = pre.codigocurso
    order by nombrecompleto

那是我的查询,这是我的功能

CREATE OR REPLACE FUNCTION fn_lisMatricula() RETURNS SETOF Matricula AS
$BODY$
DECLARE
    r Matricula%rowtype;
r Persona%rowtype;

BEGIN
    FOR r IN SELECT mat.codigo as codmatr, mat.codigoalumno as codal, mat.codigoempresa as codemp ,mat.codigopresentacion as codpre,
    mat.codigosecretaria as codsec, mat.fecha as fechamat, mat.estado as estadomat,
    mat.vigencia as vigmat, p.apellidos as apeAl, p.apellidos||' '||p.nombres as nombrecompleto,
    p.nombres as nomAl,razonsocial ,pre.codigocurso as codcur,cur.nombre as curso
    FROM matricula mat join alumno al on mat.codigoalumno = al.codigoalumno
    join persona p on  al.codigoalumno = p.codigo
    join persona pe on mat.codigoalumno = pe.codigo
    left join empresa emp on mat.codigoempresa = emp.codigo
    join presentacion pre on mat.codigopresentacion = pre.codigo
    join curso cur on cur.codigo = pre.codigocurso
    order by nombrecompleto
    LOOP       
        RETURN NEXT r;
    END LOOP;
    RETURN;
END
$BODY$
LANGUAGE 'plpgsql';

select * from fn_lisMatricula()

问题是函数的结果只有我的“矩阵”表的结构,但我想要所有查询结果的结构。

4

1 回答 1

2

使用RETURNS TABLE并指定结果列类型和名称。请参阅PL/PgSQLCREATE FUNCTION.

或者,您可以:

  • CREATE TYPE用于目的的自定义复合类型并返回SETOF它;
  • 使用OUT参数和RETURNS SETOF RECORD,
  • RETURNS SETOF RECORD调用函数时使用并指定结果记录结构

RETURNS TABLE(...)是迄今为止最简单的选择。

于 2013-04-01T07:29:32.597 回答