简体   繁体   中英

Do we need transaction with more than one update in same query?

I have one query with 2 updates and 1 delete. I want do all that with one executeNonQuery. Do I need transaction in case like this?

Public Shared Sub Remove(ByRef userData As IUser, ByVal itemID As Integer)
        Dim conn As DbConnection = DbProvider.GetDbConnection(ConnectionStringHelper.GetConnectionString(userData))
        Dim cmd As DbCommand

        Const SQL As String = " UPDATE d " _
                            & "     SET DescriptionID = null  " _
                            & "     FROM table1 AS d " _
                            & "     WHERE DescriptionID = @itemID " _
                            & " UPDATE cv " _
                            & "     SET DescriptionID = null " _
                            & "     FROM table2 AS cv " _
                            & "     WHERE DescriptionID = @itemID " _
                            & " DELETE FROM table3" _
                            & "     WHERE ItemID=@itemID AND CandidateID = @UserID AND CandidateID IS NOT NULL "

        cmd = DbProvider.GetDbCommand(SQL, conn)
        cmd.Parameters.Add("@ItemID", DbType.Int32).Value = itemID
        cmd.Parameters.Add("@UserID", DbType.Int32).Value = userData.UserID

        Try
            conn.Open()
            cmd.ExecuteNonQuery()

        Finally
            conn.Close()
            conn.Dispose()
            cmd.Dispose()
        End Try
    End Sub

Thanks for help.

It depends from answer on the question. Will you (or your company/client) loose (miscalculate/miss/omit) something , if two updates will be successful, and delete not? Or if first update will be successful, and second update will not be successful and Delete will be successful. If the answer is yes, then yes, you need Transaction. And if execution of three operations on db is not bringing any inconsistency, then you don't need Transaction.

It looks like your command will execute within a single, implicit transaction anyway. So, unless you want to roll it all back, no you do not 'need' an explicit transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM