自用小經驗(2)–oracle使用遊標可以支援結果集

來源:互聯網
上載者:User

 Oracle 預存程序可以支援結果集,

 暫時還沒有考證對於大資料量查詢來說,使用這種方式直接返回OracleDataReader,

 是否比通過其它方式(如視圖)速度來得更快.


下面說明如何使用 DataReader 來訪問由預存程序 SELECT_JOB_HISTORY 返回的結果集。

以下為包規範:

CREATE OR new PACKAGE SELECT_JOB_HISTORY AS

TYPE T_CURSOR IS REF CURSOR;

PROCEDURE GetJobHistoryByEmployeeId

(

    p_employee_id IN NUMBER,

    cur_JobHistory OUT T_CURSOR

);

END SELECT_JOB_HISTORY;

包本文定義了一個過程,該過程檢索指定員工的工作經曆的結果集,並將其作為 REF CURSOR 輸出參數返回:

CREATE OR new PACKAGE BODY SELECT_JOB_HISTORY AS

PROCEDURE GetJobHistoryByEmployeeId

(

    p_employee_id IN NUMBER,

    cur_JobHistory OUT T_CURSOR

)

IS

BEGIN

    OPEN cur_JobHistory FOR

    SELECT * FROM JOB_HISTORY

        WHERE employee_id = p_employee_id;

END GetJobHistoryByEmployeeId;

END SELECT_JOB_HISTORY;

以下代碼執行該過程,根據結果集建立 DataReader,並將 DataReader 的內容輸出到控制台。

// create connection

OracleConnection conn = new OracleConnection("Data Source=oracledb;

    User Id=UserID;Password=Password;");

// create the command for the stored procedure

OracleCommand cmd = new OracleCommand();

cmd.Connection = conn;

cmd.CommandText = "SELECT_JOB_HISTORY.GetJobHistoryByEmployeeId";

cmd.CommandType = CommandType.StoredProcedure;

// add the parameters for the stored procedure including the REF CURSOR

// to retrieve the result set

cmd.Parameters.Add("p_employee_id", OracleType.Number).Value = 101;

cmd.Parameters.Add("cur_JobHistory", OracleType.Cursor).Direction =

    ParameterDirection.Output;

// open the connection and create the DataReader

conn.Open();

OracleDataReader dr = cmd.ExecuteReader();

// output the results and close the connection.

while(dr.Read())

{

    for(int i = 0; i < dr.FieldCount; i++)

        Console.Write(dr[i].ToString() + ";");

    Console.WriteLine();

}

conn.Close();

對於 HR 架構的預設安裝,控制台輸出顯示了員工 101 的兩個記錄中每個記錄的欄位(用分號分隔):

101;9/21/1989 12:00:00 AM;10/27/1993 12:00:00 AM;AC_ACCOUNT;110;

101;10/28/1993 12:00:00 AM;3/15/1997 12:00:00 AM;AC_MGR;110;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.