oracle建立預存程序並返回結果集(附C#調用代碼)

來源:互聯網
上載者:User

標籤:

使用預存程序中,最常用的莫過於查詢資料表,並返回結果集。

在SQL SERVER 中,這類操作最簡單,通過簡單的select * from xx 即可完成。但是在Oracle中並不支援這種寫法,那麼我們怎麼實現跟SQL SERVER同樣的功能呢?且看以下代碼:

create or replace procedure sp_getdept(rep_type in varchar2,sel in varchar2,result out sys_refcursor)as     seq varchar2(40);     info varchar2(40);begin    if rep_type = ‘1‘ then          open result for select * from help;     end IF;     if rep_type = ‘2‘ then        select seq,info into seq,info from help where rownum=1;     end if;end;

通過代碼可以看到,oracle中通過遊標sys_refcursor實現返回一個table格式的結構集。注意定義方式result out sys_refcursor,跟C#中out 參數類型有點類似。

sys_refcursor和 cursor 比較:

sys_refcursor不能用open,close ,fetch 進行操作。可以用作參數。

cursor可以用 open,close ,fetch操作。不可以用作參數。

 

下面是C#調用上例預存程序的代碼:

 OracleConnection con = new OracleConnection("Password=manager;User ID=SYSTEM;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));");            OracleCommand cmd = new OracleCommand("sp_getdept", con);            cmd.CommandType = CommandType.StoredProcedure;            OracleParameter p0 = new OracleParameter("rep_type", OracleType.VarChar);            p0.Direction = ParameterDirection.Input;            cmd.Parameters.Add(p0);            cmd.Parameters["rep_type"].Value = "2";            OracleParameter p1 = new OracleParameter("result", OracleType.Cursor);            p1.Direction = System.Data.ParameterDirection.Output;            cmd.Parameters.Add(p1);            OracleParameter p2 = new OracleParameter("sel", OracleType.VarChar);            p0.Direction = ParameterDirection.Input;            cmd.Parameters.Add(p2);            cmd.Parameters["sel"].Value = "1";            OracleDataAdapter da = new OracleDataAdapter(cmd);            DataSet ds = new DataSet();            da.Fill(ds);            Console.WriteLine(ds.Tables[0].Rows[5][0].ToString());            Console.ReadLine();

希望能對您有所協助。^_^。

 

oracle建立預存程序並返回結果集(附C#調用代碼)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.