Oracle SQL创建返回表的函数或过程

时间:2016-04-24 17:08:09

标签: sql oracle function stored-procedures plsql

在SQL Server中,我可以使用'RETURNS TABLE'来完成这项工作。但我无法在Oracle SQL中找到如何做同样的事情

我有以下需要放入函数或过程的SELECT语句:

SELECT a.CodAcord, a.Descr
FROM FreqSoce f
LEFT JOIN Acord a ON a.CodAcord = f.CodAcord
WHERE f.codSoce = codSoce;

codSoce是一个INTEGER IN参数,我需要从我的函数/过程返回a.CodAcorda.Descr
有一个简单的方法吗?无需处理临时变量和/或高级内容......

编辑:有条件的信息:
  - 我需要返回a.CodAcorda.Descr,但是当我做一些研究以了解如何使用SQL函数或过程返回多个变量时,我所能找到的只是返回一张桌子。如果有办法从功能或程序中返回多个项目,请告诉我   - 严格要求使用功能或程序   - 我正在使用SQL Developer。

2 个答案:

答案 0 :(得分:0)

将以下内容作为代码模板:

CREATE OR REPLACE PACKAGE tacord AS
    TYPE ttabAcord IS TABLE OF ACord%ROWTYPE;
END tacord;
/
show err

CREATE OR REPLACE PACKAGE BODY tacord AS
BEGIN
    NULL;
END tacord;
/
show err

CREATE OR REPLACE FUNCTION demo RETURN tacord.ttabAcord AS
    to_return   tacord.ttabAcord;
BEGIN
               SELECT a.*
    BULK COLLECT INTO to_return
                 FROM FreqSoce f
            LEFT JOIN Acord a ON a.CodAcord = f.CodAcord
                WHERE f.codSoce = codSoce
                    ;
    RETURN to_return;
END demo;
/
show err

关键点:

  • %ROWTYPE表示数据库表记录的数据类型
  • BULK COLLECT INTO将完整的结果集插入到plsql数据结构中
  • plsql集合方法可以对表内容进行迭代,即.FIRST.LAST.NEXT

答案 1 :(得分:0)

您可以使用流水线表函数将函数表作为函数的返回值。请参阅以下示例:

-- Create synthetic case
CREATE TABLE Acord AS
SELECT rownum CodAcord, 'Description ' || rownum Descr
  FROM dual CONNECT BY LEVEL <= 5;

CREATE TABLE FreqSoce AS
SELECT rownum CodSoce, rownum CodAcord
  FROM dual CONNECT BY LEVEL <= 10;

-- Test dataset
SELECT a.CodAcord, a.Descr
  FROM FreqSoce f
  LEFT JOIN Acord a ON a.CodAcord = f.CodAcord
 WHERE f.CodSoce = 10;

-- Here begins actual code
-- Create an object type to hold each table row
CREATE OR REPLACE TYPE typ_acord AS OBJECT(
  CodAcord NUMBER,
  Descr    VARCHAR2(40)
);
/

-- Create a collection type to hold all result set rows
CREATE OR REPLACE TYPE tab_acord AS TABLE OF typ_acord;
/

-- Our function that returns a table
CREATE OR REPLACE FUNCTION getAcord(pCodSoce IN NUMBER)
RETURN tab_acord PIPELINED
AS
BEGIN
  FOR x IN (SELECT a.CodAcord, a.Descr
              FROM FreqSoce f
              LEFT JOIN Acord a ON a.CodAcord = f.CodAcord
             WHERE f.CodSoce = pCodSoce)
  LOOP
    PIPE ROW (typ_acord(x.CodAcord, x.Descr));
  END LOOP;
END;
/

-- Testing the function (please note the TABLE operator)
SELECT * FROM TABLE(getAcord(5));