下面的例子我们用存储过程返回两个数据集,然后用DataReader的NextResult方法处理这两个数据集。
存储过程的代码(名称:Proc):
CREATE PROC Proc —-Multiple Resultsets
AS
SELECT * FROM Users
SELECT * FROM Users WHERE State = ‘CA‘
GO
取这两个数据集的代码:
注意DataReader的NextResult出现的地方
String ConnString = "User ID=sa;password=sa;Initial Catalog=pubs;Data Source=myServer";SqlConnection Connection = new SqlConnection(myConnString);SqlCommand Command = new SqlCommand();SqlDataReader reader ;Command.CommandType = CommandType.StoredProcedure;Command.Connection = Connection;Command.CommandText = "Proc";int RecordCount=0;try{Connection.Open();reader = command.ExecuteReader();int RecordCount=0;// read the data from that resultset while (reader.Read()){RecordCount = RecordCount + 1;}Response.Write("Total number of Users:" + RecordCount.ToString());// read the next resultset reader.NextResult();RecordCount = 0;// read the data from that second resultset while (reader.Read()){RecordCount = RecordCount + 1;}Response.Write("Total number of Users from California:" + RecordCount.ToString());}catch (Exception ex){MessageBox.Show(ex.ToString());}finally{Connection.Close();}