SqlTransaction has completed

前端 未结 9 1484
后悔当初
后悔当初 2020-12-03 10:05

I have an application which potentially does thousands of inserts to a SQL Server 2005 database. If an insert fails for any reason (foreign key constraint, field length, etc

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 11:07

    Difficult to help without seeing code. I assume from your description you are using a transaction to commit after every N inserts, which will improve performance vs committing each insert provided N is not too big.

    But the downside is: if an insert fails, any other inserts within the current batch of N will be rolled back when you rollback the transaction.

    In general you should dispose a transaction before closing the connection (which will rollback the transaction if it hasn't been committed). The usual pattern looks something like the following:

    using(SqlConnection connection = ...)
    {
        connection.Open();
        using(SqlTransaction transaction = connection.BeginTransaction())
        {
            ... do stuff ...
            transaction.Commit(); // commit if all is successful
        } // transaction.Dispose will be called here and will rollback if not committed
    } // connection.Dispose called here
    

    Please post code if you need more help.

提交回复
热议问题