存储过程返回多个结果集,但结果集的数量不固定

时间:2011-02-15 02:42:33

标签: c# stored-procedures sqldatareader

我有一个存储过程,它返回多个结果集的可变数量。如果不存在下一个结果集,DataReader.NextResult()会给出错误。如何查找是否存在下一个结果集。

2 个答案:

答案 0 :(得分:4)

如果有更多结果集,则NextResult()方法返回true - 在进行下一次读取之前检查

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.nextresult.aspx

答案 1 :(得分:0)

(我知道这是一篇旧帖子,但希望这对某人有帮助!)

如果您需要处理未知数量的结果集,可以执行以下操作:

// Need to wrap the while loop in a do-while loop due to the way Read() works versus NextResult().
// Read() moves to the next record, if any, starting with the first record.
// NextResult() moves to the next result set, if any, starting with the second result set (i.e., first result set is used automatically).
do
{
    while (mySqlDataReader.Read())
    {
        // Do some processing here...for example:

        var rowValues = new object[mySqlDataReader.FieldCount];
        mySqlDataReader.GetValues(rowValues);

        foreach (var element in rowValues)
        {
            myStringBuilder.Append(element).Append(" | ");
        }

        myStringBuilder.AppendLine();
    }
}
while (mySqlDataReader.NextResult());
相关问题