mercredi 27 mai 2015

How is it possible to have changes in a database available at a later stage inside a local transaction?

I have a vb.net application that updates a record in table A and then inserts a record in the same table, inside a local transaction (in SQL Server 2005.)

_DbConnection.Open()
Try
    _Transaction = _DbConnection.BeginTransaction()

    If _DbConnection.State = ConnectionState.Open Then

        bProcessSuccessfully = Update()

        _Transaction.Commit()
    End If
Catch ex As Exception
    Try
        _Transaction.Rollback()
    Catch ex2 As Exception
        Logger.Error(ex2.Message)
    End Try
Finally
    _DbConnection.Close()
End Try

The Update method updates a field (lets call it ID) which has a unique constraint and sets it to a new unique value. Then it proceeds to insert a new record in the table using the old value of field ID.

For example if field ID has the value 0542-70-00002, the existing record is updated with ID=0542-70-00002/S and a new record is inserted with ID=0542-70-00002.

The problem is that when trying to insert the new record I get an exception Violation of UNIQUE KEY constraint 'UF_ID'. Cannot insert duplicate key in object 'A'.

The code above does not fail all the time. In fact until today was not failing at all. I made sure (using git's log) that no changes were made to this code that could cause this change in its behavior.

So the question is, what needs to be done to make the updated value of field ID visible when the insertion is performed in order to succeed? Both the update and the insertion need to be performed inside a transaction, since I need an all-or-nothing operation.

I have tried specifying a different isolation level in BeginTransaction (ReadCommited and ReadUncommited), but the problem persists.

Aucun commentaire:

Enregistrer un commentaire