I have two SqlCommand
which I want use both in a single method, thus I don't understand why it didn't work. This method will simultaneously update a Column based on every Read()
ItemId
.
Is it even possible for me to execute SqlCommand
during SqlDataReader.Read()
?
Here's the exception I got:
There is already an open DataReader associated with this Command which must be closed first.
My code:
private void UpdateStock()
{
string thisUpdateCommandText = "UPDATE [Item] SET [Stock] += @Quantity WHERE [ItemId] = @ItemId";
string thisSelectCommandText = "SELECT [ItemId], [Quantity] FROM [PackageItem] WHERE [PackageId] = @PackageId";
using (SqlConnection thisSqlConnection = new SqlConnection(theConnectionString))
using (SqlCommand thisSelectSqlCommand = new SqlCommand(thisSelectCommandText, thisSqlConnection))
{
thisSqlConnection.Open();
thisSelectSqlCommand.Parameters.Add("@PackageId", SqlDbType.Int).Value = thePackageId;
using (SqlDataReader thisSqlDataReader = thisSelectSqlCommand.ExecuteReader())
{
while (thisSqlDataReader.Read())
{
using (SqlCommand thisUpdateSqlCommand = new SqlCommand(thisUpdateCommandText, thisSqlConnection))
{
thisUpdateSqlCommand.Parameters.Add("@ItemId", SqlDbType.Int).Value = thisSqlDataReader.GetInt32(0);
thisUpdateSqlCommand.Parameters.Add("@Quantity", SqlDbType.Int).Value = thisSqlDataReader.GetInt32(1);
thisUpdateSqlCommand.ExecuteNonQuery();
}
}
}
}
}