Oracle PL SQL过程等同于Sequel / Sybase中的T SQL

时间:2014-06-11 07:50:33

标签: sql-server oracle stored-procedures plsql sybase

我是Oracle新手。来自SQL / Sybase背景,并努力创建一个只需从表中输出一组字段的过程。 我希望在Oracle中创建一个与SQL / Sybase等效的存储过程,如下所示;

CREATE PROCEDURE ListTransactions @StartDate datetime, @EndDate datetime AS
DECLARE @ReportDate datetime
SET @ReportDate = CONVERT(datetime,CONVERT(VARCHAR,GETDATE(), 103), 103)
SELECT
   @ReportDate,
   trn.TransactionDate,
   cp.CounterPartyName,
   cu.Currency_Name,
   trn.Amount,
   trn.PostedBy,
   trn.Comments
FROM
   Transactions trn
   LEFT JOIN CounterParties cp ON trn.CounterParty_Id = cp.CounterParty_Id
   LEFT JOIN Currency cu ON trn.Currency_Id = cu.Currency_Id
WHERE
   trn.TransactionDate Between @StartDate AND @EndDate

1 个答案:

答案 0 :(得分:1)

以下内容应该像你想要的那样:

CREATE OR REPLACE FUNCTION LIST_TRANSACTIONS(pStartDate IN DATE,
                                             pEndDate   IN DATE)
  RETURN SYS_REFCURSOR IS
DECLARE
  csr SYS_REFCURSOR;
BEGIN
  OPEN csr FOR
    SELECT TRUNC(SYSDATE),
           trn.TransactionDate,
           cp.CounterPartyName,
           cu.Currency_Name,
           trn.Amount,
           trn.PostedBy,
           trn.Comments
      FROM Transactions trn
      LEFT OUTER JOIN CounterParties cp
        ON trn.CounterParty_Id = cp.CounterParty_Id
      LEFT OUTER JOIN Currency cu
        ON trn.Currency_Id = cu.Currency_Id
      WHERE trn.TransactionDate BETWEEN pStartDate
                                    AND pEndDate;
  RETURN csr;
END LIST_TRANSACTIONS;

我不明白你的意思是“从表格中输出一组字段”。此函数将返回调用者随后可以迭代的游标。例如,如果要将游标的结果转储到DBMS_OUTPUT,则可以执行类似以下匿名块的操作:

DECLARE
  c                    SYS_REFCURSOR;
  dtDate               DATE;
  dtTransaction_date   DATE;
  strCounterPartyName  VARCHAR2(100);
  strCurrency_Name     VARCHAR2(100);
  nAmount              NUMBER;
  strPostedBy          VARCHAR2(100);
  strComments          VARCHAR2(2000);
BEGIN
  c := LIST_TRANSACTIONS(pStartDate => SYSDATE - INTERVAL '1' MONTH,
                         pEndDate   => SYSDATE);

  LOOP
    FETCH c
      INTO dtDate,
           dtTransaction_date,
           strCounterPartyName,
           strCurrency_Name,
           nAmount,
           strPostedBy,
           strComments;

    EXIT WHEN c%NOTFOUND;

    DBMS_OUTPUT.PUT_LINE('Date=' || dtDate || 
                         'Transaction date=' || dtTransaction_date ||
                         'Counter-party namme=' || strCounterPartyName ||
                         'Currency name=' || strCurrency_Name ||
                         'Amount=' || nAmount ||
                         'Posted by=' || strPostedBy ||
                         'Comments=' || strComments);
  END LOOP;

  CLOSE c;
END;

未在动物身上进行测试 - 您将成为第一个!

分享并享受。