2013-04-01 70 views
0

我有一個問題,我有一個查詢,具有多個表,我想創建一個返回我查詢作爲表如何從查詢中的函數postgresql和多個表中返回一個表?

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() 

問題是函數的結果只有我的「matricula」表的結構,但我想要我的所有查詢結果的結構。

+0

您是否嘗試過使用該視圖創建視圖,然後使用視圖intead? – Horus

+0

對不起,我無法理解你的問題。也許你正在尋找[這樣的東西?](http://stackoverflow.com/questions/11740256/refactor-a-pl-pgsql-function-to-return-the-output-of-various-select-queries/ 11751557#11751557)? –

+0

我想返回一個表與我的查詢的列,該查詢有超過2個表我怎麼能做到這一點? – MitoCode

回答

2

使用RETURNS TABLE並指定結果列類型和名稱。見the PostgreSQL documentation for PL/PgSQLCREATE FUNCTION

或者,您可以:

  • CREATE TYPE定製的複合型爲宗旨,並返回一個SETOF它;
  • 使用OUT參數和RETURNS SETOF RECORD
  • 使用RETURNS SETOF RECORD和調用功能

RETURNS TABLE(...)是迄今爲止這些最簡單的選項時,指定結果記錄結構。

+0

是的,我讀了somethig關於退貨表,但我不知道它是如何工作的,我鍵入一些代碼返回表,但沒有奏效,你能寫我一個示例代碼返回表?一個容易的人請。謝謝=) – MitoCode

+0

@ J.A。不,我不會寫一個例子。您可以在Stack Overflow,PostgreSQL文檔和其他地方找到很多示例。從這裏開始:http://stackoverflow.com/search並在這裏:http://google.com/ –

相關問題