Basic template for Transactions in sqlserver

前端 未结 4 1687
南笙
南笙 2020-12-23 23:24

If I simply wrap my query with:

BEGIN TRANSACTION



COMMIT TRANSACTION

If anything fails inside of that, will it automatically rollback?

4条回答
  •  离开以前
    2020-12-23 23:32

    For transaction control you use begin, commit and rollback. You begin a transaction by supplying BEGIN TRANSACTION. Then you put the various SQL statements you need. Then you end the transaction by issuing either a commit or rollback. COMMIT TRANSACTION will commit all the changes that you did to the database after the BEGIN statement and make them permanent, so to speak. ROLLBACK TRANSACTION will rollback all changes that you did to the database after the BEGIN statement. However, it will not change variable values.

    Example:

    BEGIN TRANSACTION
    
    UPDATE table SET column = 'ABC' WHERE column = '123'
    
    COMMIT TRANSACTION
    
    --//column now has a value of 'ABC'
    
    BEGIN TRANSACTION
    
    UPDATE table SET column = 'ABC' WHERE column = '123'
    
    ROLLBACK TRANSACTION
    
    --//column still has it's previous value ('123') No changes were made.
    

提交回复
热议问题