我有以下代碼。SqlDataReader和SqlCommand
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 。
我需要讀取返回的每一行,對數據做一些驗證並在必要時進行更新,然後繼續到下一條記錄。如果我在使用reader.Read()
循環時不能使用SqlCommand
,我該如何實現這一目標?
格蘭特托馬斯的回答是正確的,但它會更有效地記錄您希望設置爲不活動的每個記錄的PK,然後執行單個UPDATE ... WHERE IN(...)讀者。 – Phil 2013-02-21 15:36:55
有趣......就像建立一個PK的數組,你的意思是然後循環通過? – Stuart 2013-02-21 15:41:07
爲什麼你需要選擇並循環每個更新?爲什麼不直接使用select語句的where子句進行更新? – adrianm 2013-02-21 18:19:37