As has been pointed out, you never assign your transaction to the command. However there are a few other points I have picked up on.
First and foremost USE PARAMETRISED QUERIES, they will improve performace, type safety and most importantly save you from SQL Injection Attacks.
So instead of:
comando.CommandText = "UPDATE RECURSO_CLIENTE SET NM_CLIENTE = " + arr[j].Col3 + " WHERE CD_RECURSO = " + arr[j].Col1;
You would use:
comando.CommandText = "UPDATE RECURSO_CLIENTE SET NM_CLIENTE = @Col3 WHERE CD_RECURSO = @Col1"; comando.Parameters.AddWithValue("@Col3", arr[j].Col3); comando.Parameters.AddWithValue("@Col1", arr[j].Col1);
Secondly, wrap your sql command object with a using wrapper to ensure it is properly dispose of, there is no benefit from reusing the same object over and over again (and this can cause problems):
for (int j = 0; j < arr.Length; j++) { using (var comando = new SqlCommand("UPDATE RECURSO_CLIENTE SET NM_CLIENTE = @Col3 WHERE CD_RECURSO = @Col1", conexao)) { comando.Transaction = trx; comando.Parameters.AddWithValue("@Col3", arr[j].Col3); comando.Parameters.AddWithValue("@Col1", arr[j].Col1); comando.ExecuteNonQuery(); } }
Finally, if you are using SQL-Server 2008+ you can use Table valued Parameters to do this update in a single query:
You first need a type
CREATE TABLE YourTypeName AS TABLE (Col1 INT, Col3 INT);
Then your update statement would be something like:
DECLARE @UpdateValues AS YourTypeName; MERGE RECURSO_CLIENTE rc USING @UpdateValues u ON rc.CD_RECURSO = u.Col1 WHEN MATCHED UPDATE SET NM_CLIENTE = u.Col3;
This means a single statement and you don't need to use explicit transactions. (You might wonder why I have used merge instead of UPDATE, here is why). So putting it all together you would get:
var dataTable = new DataTable(); dataTable.Columns.Add("Col1", typeof(int)); dataTable.Columns.Add("Col3", typeof(int)); for (int j = 0; j < arr.Length; j++) { var newRow = dataTable.NewRow(); newRow[0] = arr[j].Col1; newRow[1] = arr[j].Col3; dataTable.Rows.Add(newRow); } string sql = @" MERGE RECURSO_CLIENTE rc USING @UpdateValues u ON rc.CD_RECURSO = u.Col1 WHEN MATCHED UPDATE SET NM_CLIENTE = u.Col3;"; using (var conexao = new SqlConnection(WebConfigurationManager.ConnectionStrings["strConexao"].ToString())) using (var comando = new SqlCommand(sql, conexao)) { conexao.Open(); var tableParam = new SqlParameter("@UpdateValues", SqlDbType.Structured); tableParam.TypeName = "@YourTypeName"; tableParam.Value = dataTable; comando.Parameters.Add(tableParam); comando.ExecuteNonQuery(); }