我有下面的代码。
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand select = new SqlCommand("SELECT RTRIM(LTRIM(PART_NO)) AS PART_NO, record FROM [RMAData].[dbo].[IMPORTING_ORDER_EDI] WHERE sessionID = '" + Session.SessionID + "'", connection);
SqlDataReader reader = select.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (!currentPart.IsActive)
{
// this part is not active, set the active flag in sql to 0
SqlCommand update = new SqlCommand("UPDATE [RMAData].[dbo].[IMPORTING_ORDER_EDI] SET valid = 0, active = 0 WHERE record = " + reader["record"].ToString() + ";", connection);
update.ExecuteNonQuery();
}
else
{
///blah
}
}
reader.Close();
}
}但这会导致以下例外..。
System.InvalidOperationException:已经有一个与此命令相关联的开放DataReader,必须先关闭。
我需要读取返回的每一行,对数据进行一些验证,并在必要时进行更新,然后继续到下一个记录。如果在循环遍历SqlCommand时不能使用reader.Read(),那么如何实现这一点呢?
发布于 2013-02-21 18:13:20
另一种选择是不添加MultipleActiveResultSets=True --这样做会对性能造成很小的损失--如下所示:
using (SqlConnection connection = new ...))
{
connection.Open();
SqlCommand select = new SqlCommand(...);
SqlDataReader reader = select.ExecuteReader();
var toInactivate = new List<string>();
if (reader.HasRows)
{
while (reader.Read())
{
if (!currentPart.IsActive)
{
toInactivate.Add(reader["record"].ToString());
}
else
{
///blah
}
}
reader.Close();
}
SqlCommand update = new SqlCommand("UPDATE ... SET valid = 0, active = 0 " +
"WHERE record IN(" + string.Join(",", toInactivate) + ");", connection);
update.ExecuteNonQuery();
}它具有在单个SQL语句中更新所有所需记录的优点。
当然,使用EF和Linq,整个过程会更加整洁。
发布于 2013-02-21 15:31:07
可以像amending your connection string一样简单:
将MultipleActiveResultSets=True添加到连接字符串
发布于 2013-02-21 15:37:39
您需要创建多个连接实例。
,因为通常只能对连接执行一个命令。
或
照@grantThomas的建议做
也可以使用多个连接,如下所示
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand select = new SqlCommand("SELECT RTRIM(LTRIM(PART_NO)) AS PART_NO, record FROM [RMAData].[dbo].[IMPORTING_ORDER_EDI] WHERE sessionID = '" + Session.SessionID + "'", connection);
SqlDataReader reader = select.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (!currentPart.IsActive)
{
// this part is not active, set the active flag in sql to 0
using (SqlConnection connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
SqlCommand update = new SqlCommand("UPDATE [RMAData].[dbo].[IMPORTING_ORDER_EDI] SET valid = 0, active = 0 WHERE record = " + reader["record"].ToString() + ";", connection1);
update.ExecuteNonQuery();
}
}
else
{
///blah
}
}
reader.Close();
}
}https://stackoverflow.com/questions/15005974
复制相似问题