標籤:
使用預存程序中,最常用的莫過於查詢資料表,並返回結果集。
在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#調用代碼)