如何从具有多个select语句的sp中读取数据?

时间:2018-03-19 13:10:08

标签: c# sql c#-4.0

我有一个sp,

-- States
select statusid,statusdesc,statustype,isfinal,seq, tstamp from issuestatuslut order by seq

-- PRE states
select a.statusid,a.otherstate,a.statetype,b.statusdesc, a.tstamp
    from issuestatetransitionlut a, issuestatuslut b
    where a.statetype=0 and a.otherstate=b.statusid

-- POST states
select a.statusid,a.otherstate,a.statetype,b.statusdesc, a.tstamp
    from issuestatetransitionlut a, issuestatuslut b
    where a.statetype=1 and a.otherstate=b.statusid

现在您可以看到所有3个返回结果具有相同的列名称,并且出于某种原因我甚至无法更改sp中的单个单词。

现在我如何在3个不同的阅读器功能中获取所有三个select语句?

3 个答案:

答案 0 :(得分:1)

您可以......使用SqlDataReader.NextResult()方法

    while (reader.HasRows)
    {
        while (reader.Read())
        {
            //your code here
        }
        reader.NextResult();
    }

答案 1 :(得分:1)

尝试以下示例,

SqlConnection con=new SqlConnection("YourConnection String");
SqlCommand cmd=new SqlCommand();
SqlDataAdapter da=new SqlDataAdapter();
DataSet ds = new DataSet();
cmd = new SqlCommand("name of your Stored Procedure", con);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("@SuperID", id);//if you have parameters.
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();

在此之后,您可以使用

利用不同的(7)记录集
ds.Tables[0]
ds.Tables[1]
ds.Tables[2]
ds.Tables[3]
ds.Tables[4]
ds.Tables[5]
ds.Tables[6]

答案 2 :(得分:1)

您可以使用Dapper

Dapper是一个强大的ORM框架

使用QueryMultiple方法。

string sql = "[YourSPName]";

using (var connection = new new SqlConnection("Connection String"))
{
    connection.Open();

    using (var multi = connection.QueryMultiple(sql, param: { }, commandType: CommandType.StoredProcedure))
    {
        var List2 = reader.Read<CategoryOne>().ToList();
        var List1 = reader.Read<CategoryTwo>().ToList();
    }
}

Dapper QueryMultiple