[Oracle]高效的PL/SQL程序设计(五)--调用存储过程返回结果集
Oracle支持通过ref游标在调用存储过程后返回结果集, 使用游标在内存消耗以及时间上都要大大的优于返回数组变量的做法!
示例如下:数据库方面,建立一个Package
create or replace package ref_cur_demo is
type rc is ref cursor;
procedure ref_cursor(p_owner in varchar2,p_cursor in out rc);
end ref_cur_demo;
create or replace package body ref_cur_demo is
procedure ref_cursor(p_owner in varchar2,p_cursor in out rc)
is
begin
open p_cursor for select object_name,object_type from all_objects where owner = p_owner and rownum<3;
end;
end ref_cur_demo;
type rc is ref cursor;
procedure ref_cursor(p_owner in varchar2,p_cursor in out rc);
end ref_cur_demo;
create or replace package body ref_cur_demo is
procedure ref_cursor(p_owner in varchar2,p_cursor in out rc)
is
begin
open p_cursor for select object_name,object_type from all_objects where owner = p_owner and rownum<3;
end;
end ref_cur_demo;
程序方面使用C#建立一个小型应用程序,主要代码如下:
Oracle.DataAccess.Client.OracleConnection oracleConnection1=new OracleConnection("data source=precolm2;user id=colmtest;password=colmtest");
oracleConnection1.Open();
string strSQL = @"ref_cur_demo.ref_cursor";
Oracle.DataAccess.Client.OracleDataAdapter da = new Oracle.DataAccess.Client.OracleDataAdapter();
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand(strSQL,oracleConnection1);
cmd.CommandType = CommandType.StoredProcedure;
Oracle.DataAccess.Client.OracleParameter pram = new Oracle.DataAccess.Client.OracleParameter("p_owner",Oracle.DataAccess.Client.OracleDbType.Varchar2);
pram.Value = "COLMTEST";
cmd.Parameters.Add(pram);
Oracle.DataAccess.Client.OracleParameter pram1 = new Oracle.DataAccess.Client.OracleParameter("p_cursor",Oracle.DataAccess.Client.OracleDbType.RefCursor);
pram1.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pram1);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
this.dataGrid1.DataSource=ds.Tables[0].DefaultView;
oracleConnection1.Open();
string strSQL = @"ref_cur_demo.ref_cursor";
Oracle.DataAccess.Client.OracleDataAdapter da = new Oracle.DataAccess.Client.OracleDataAdapter();
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand(strSQL,oracleConnection1);
cmd.CommandType = CommandType.StoredProcedure;
Oracle.DataAccess.Client.OracleParameter pram = new Oracle.DataAccess.Client.OracleParameter("p_owner",Oracle.DataAccess.Client.OracleDbType.Varchar2);
pram.Value = "COLMTEST";
cmd.Parameters.Add(pram);
Oracle.DataAccess.Client.OracleParameter pram1 = new Oracle.DataAccess.Client.OracleParameter("p_cursor",Oracle.DataAccess.Client.OracleDbType.RefCursor);
pram1.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pram1);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
this.dataGrid1.DataSource=ds.Tables[0].DefaultView;