从具有多个结果集的存储过程中检索数据

2024-04-07

给定 SQL Server 中的一个存储过程,它有多个select语句,有没有办法在调用过程时单独处理这些结果?

例如:

alter procedure dbo.GetSomething
as
begin
    select * from dbo.Person;
    select * from dbo.Car;
end;

在.NET中,如果我调用这个过程,我可以使用SqlDataReader在两个结果集之间移动,这样我就可以轻松检索所有人和汽车。然而,在 SQL 中,当我直接执行过程时,我会得到两个结果集。

如果我打电话:

insert @myTempTable
    exec dbo.GetSomething;

然后它会出错,因为列定义不匹配。如果碰巧 Person 和 Car 有相同的列,它会将两者连接在一起,@myTempTable 会从两个表中获取所有记录,这显然也不好。

我可以定义代表两个结果集的新自定义类型,并制作这些输出参数,而不是使用多个select语句,但我想知道是否有更好的方法 - 将两个结果拉入临时表或循环结果等的某种方法。

EDIT

实际上,仔细观察后,即使是输出表参数也无法解决这个问题 - 它们是只读的,在 SQL 2012 中仍然如此。(连接票证要求添加此内容 https://connect.microsoft.com/SQLServer/feedback/details/299296/relax-restriction-that-table-parameters-must-be-readonly-when-sps-call-each-other)


To 使用 DataReader 和 NextResult 检索多个结果集 https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader#retrieving-multiple-result-sets-using-nextresult你可以这样做

String myConStr  
          ="User ID="user";password="pass";Initial Catalog=pubs;Data Source=Server";
SqlConnection myConnection = new SqlConnection(myConStr);
SqlCommand myCommand = new SqlCommand();
SqlDataReader myReader;

myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Connection = myConnection;
myCommand.CommandText = "MyProc";
     
try
{
   myConnection.Open();
   myReader = myCommand.ExecuteReader();

   while (myReader.Read())
   {
      // write logic to process data for the first result.   
   }
    
   myReader.NextResult();
   while (myReader.Read())
   {
      // write logic to process data for the second result.
   }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从具有多个结果集的存储过程中检索数据 的相关文章

随机推荐