您不使用一个连接和多个命令(实际上是在循环中重新创建一个命令)的原因是什么?也许此解决方案将为您工作:
public static void CommandExecNonQuery(SqlCommand cmd, string query, SqlParameter[] prms) { cmd.CommandText = query; cmd.Parameters.AddRange(prms); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } static void Main(string[] args) { string insertQuery = @"INSERT TESTTABLE (COLUMN1, COLUMN2) " + "VALUES(@ParamCol1, @ParamCol2)"; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = connection.CreateCommand()) { SqlTransaction transaction = null; try { // BeginTransaction() Requires Open Connection connection.Open(); transaction = connection.BeginTransaction(); // Assign Transaction to Command command.Transaction = transaction; for (int i = 0; i < 100; i++) CommandExecNonQuery(command, insertQuery, new SqlParameter[] { new SqlParameter("@ParamCol1", i), new SqlParameter("@ParamCol2", i.ToString()) }); transaction.Commit(); } catch { transaction.Rollback(); throw; } finally { connection.Close(); } } } }
另请参见 Sql Server事务-ADO.NET 2.0-提交和回滚-使用语句- IDisposable