将NextResult函数与datareader一起使用时发生错误
无法获取第二个表结果,并且在第二个NextResult行上出错 ” 关闭阅读器时,无效尝试调用nextresult “
using (SqlConnection myCon = DBCon)
{
try
{
string Qry = @"SELECT [OPSProcedure],[OPSInsertedOn],[OPSInsertedBy]
FROM [Operation] where OPSID = '" + opId + "';";
Qry += @"SELECT LKCPID FROM dbo.ConcurrentProcedure where CPOperationID = '" + opId + "';";
Qry += @"SELECT IOperaitonID FROM dbo.LkupIntraOperativeAdverseEvents where IOperaitonID = '" + opId + "';";
myCon.Open();
SqlCommand myCommand = new SqlCommand(Qry, myCon);
myCommand.CommandType = CommandType.Text;
SqlDataReader sqlReader = myCommand.ExecuteReader();
DataSet dr = new DataSet();
if (sqlReader.HasRows)
{
dt1.Load(sqlReader);
if(sqlReader.NextResult())
{
dt2.Load(sqlReader);
}
if (sqlReader.NextResult())
{
dt3.Load(sqlReader);
}
}
sqlReader.Close();
}
catch (Exception ex)
{
}
}
我尝试过的事情:
我尝试使用以下代码获得多个结果
答案 0 :(得分:1)
在这种情况下,我将仅使用SqlDataAdapter进行一次调用并填充所有表
using (SqlConnection myCon = DBCon)
{
try
{
string Qry = @"SELECT [OPSProcedure],[OPSInsertedOn],[OPSInsertedBy]
FROM [Operation] where OPSID = @id;
SELECT LKCPID FROM dbo.ConcurrentProcedure
where CPOperationID = @id;
SELECT IOperaitonID FROM dbo.LkupIntraOperativeAdverseEvents
where IOperaitonID = @id";
myCon.Open();
SqlDataAdapter da = new SqlDataAdapter(Qry, myCon);
da.SelectCommand.Parameter.Add("@id", SqlDbType.NVarChar).Value = opID;
DataSet ds = new DataSet();
da.Fill(ds);
// Test...
Console.WriteLine(ds.Tables[0].Rows.Count);
Console.WriteLine(ds.Tables[1].Rows.Count);
Console.WriteLine(ds.Tables[2].Rows.Count);
还请注意,您绝对不要连接字符串来构建sql命令。始终使用参数。
答案 1 :(得分:0)
DataTable.Load
如果sqlReader
为sqlReader.IsClosed
且false
返回NextResults
(根据this forum),则false
关闭。
因此,而不是:
if (sqlReader.NextResult())
您需要使用:
if (!sqlReader.IsClosed && sqlReader.NextResult() && sqlReader.HasRows)