面对存储过程返回多个结果集,我们在.NET
应用程序中如何处理呢?
脚本如下:
CREATE PROCEDURE PROCEDURENAME AS BEGIN BEGIN IF OBJECT_ID('TABLE1') IS NOT NULL DROP TABLE TABLE1 CREATE TABLE TABLE1 (ID INT PRIMARY KEY IDENTITY(1,1),[NAME] VARCHAR(50),AGE INT) INSERT INTO TABLE1 ([NAME],AGE) VALUES('大卫1',50) INSERT INTO TABLE1 ([NAME],AGE) VALUES('约翰1',35) IF OBJECT_ID('TABLE2') IS NOT NULL DROP TABLE TABLE2 CREATE TABLE TABLE2 (ID INT PRIMARY KEY IDENTITY(1,1),[NAME] VARCHAR(50),AGE INT) INSERT INTO TABLE2 ([NAME],AGE) VALUES('大卫2',50) INSERT INTO TABLE2 ([NAME],AGE) VALUES('约翰2',35) IF OBJECT_ID('TABLE3') IS NOT NULL DROP TABLE TABLE3 CREATE TABLE TABLE3 (ID INT PRIMARY KEY IDENTITY(1,1),[NAME] VARCHAR(50),AGE INT) INSERT INTO TABLE3 ([NAME],AGE) VALUES('大卫3',50) INSERT INTO TABLE3 ([NAME],AGE) VALUES('约翰3',35) IF OBJECT_ID('TABLE4') IS NOT NULL DROP TABLE TABLE4 CREATE TABLE TABLE4 (ID INT PRIMARY KEY IDENTITY(1,1),[NAME] VARCHAR(50),AGE INT) INSERT INTO TABLE4 ([NAME],AGE) VALUES('大卫4',50) INSERT INTO TABLE4 ([NAME],AGE) VALUES('约翰4',35) END BEGIN SELECT * FROM TABLE1 //数据集1 SELECT * FROM TABLE2 //数据集2 SELECT * FROM TABLE3 //数据集3 SELECT * FROM TABLE4 //数据集4 END END
代码如下:
public DataSet GetProcedureName(out string out outVal) { using(var db = new Entities()) { var command=db.Database.Connection.CreateCommand(); //创建command的链接 command.CommandType = CommandType.StoredProcedure; //指向CommandType 为存储过程类型 command.CommandText = "PROCEDURENAME"; //存储过程名称 command.Parameters.AddRange(new SqlParameter[]{ new SqlParameter("paraKey1",paraVal1),//输入参数 new SqlParameter("paraKey2",paraVal2) //输出参数 { Direction = ParameterDirection.Output, //指向该参数是输出参数 SqlDbType = SqlDbType.VarChar, //输出参数的类型 Size = 200 //输出参数的大小 }, }); using(var adapter=new SqlDataAdapter(command as SqlCommand)) { DataSet dataSet = new DataSet();//声明数据集 adapter.Fill(dataSet); //添加数据集 outVal = command.Parameters[1].Value.ToString(); return dataSet; //返回数据集 } } }
.NET
WEBAPI
中调用代码如下:
public HttpResponseMessage GetProcedureName() { DataSet result = new DataSet(); //声明数据集 result = GetProcedureName(); //调用方法 return Json(new APIResultModel() { result = new { data1 = result.Tables[0], data2 = result.Tables[1], data3 = result.Tables[2], data4 = result.Tables[3], } }); }
使用此方法,可以完全避免EF
对存储过程的更新。我们只需要专注于存储过程即可。