Using transaction on a single update statement

前端 未结 3 862
执念已碎
执念已碎 2021-02-07 13:09

I am dubbing some SP at work and I have discover that whoever wrote the code used a transaction on a single update statement like this

begin transaction 
*single         


        
3条回答
  •  广开言路
    2021-02-07 13:18

    Hopefully your colleague's code looks more like this, otherwise SQL will issue a syntax error. As per Ypercube's comment, there is no real purpose in placing one statement inside a transaction, but possibly this is a coding standard or similar.

    begin transaction  -- Increases @@TRANCOUNT to 1
    update table whatever with whatever
    commit transaction  -- DECREMENTS @@TRANCOUNT to 0
    

    Often, when issuing adhoc statements directly against SQL, it is a good idea to wrap your statements in a transaction, just in case something goes wrong and you need to rollback, i.e.

    begin transaction -- Just in case my query goofs up
    update table whatever with whatever
    select ... from table ... -- check that the correct updates / deletes / inserts happened
    -- commit transaction  -- Only commit if the above check succeeds.
    

提交回复
热议问题