Can anybody help me rewrite the code below so that I don't have to loop around the update command? In T-SQL, I would do:
UPDATE MyTable
SET MyCol = 'MyVal'
WHERE key IN (SELECT someKey FROM someOtherTable)
but I can't seem to get my head around this in C#. The someOtherTable
is in memory if that is significant.
Thanks,
Palle
public static void UpdateDb()
{
var myKeys = someOtherTable.AsEnumerable()
.Select(r => r.Field<int>("id")).ToList();
const string updateTable = "UPDATE myTable SET myCol = 'myVal' WHERE id = @id";
using (SqlConnection sqlConnection = new SqlConnection(SqlConnectionString))
{
sqlConnection.Open();
foreach (int myId in myKeys)
{
SqlCommand cmd = new SqlCommand(updateTable, sqlConnection);
cmd.Parameters.AddWithValue("@id", myId);
cmd.ExecuteNonQuery());
}
sqlConnection.Close();
}
}