Wednesday, April 8, 2015

What are ROLLBACK WORK AND COMMIT WORK?

I am sure that you are familiar with ROLLBACK TRANSACTION and COMMIT TRANSACTION but have you heard about or used ROLLBACK WORK and COMMIT WORK?

ROLLBACK WORK and COMMIT WORK work exactly same way as ROLLBACK TRANSACTION and COMMIT TRANSACTION. WORK keyword is optional and this is ISO-compatible.

Can we use this instead what we have been used? Yea it is possible and no harm at all. Only missing part is, this does not accept user-defined transaction name.

Here is a sample code using ROLLBACK WORK and COMMIT WORK.

  1. USE AdventureWorks2014;  
  2. GO  
  3.   
  4. BEGIN TRAN  
  5.   
  6. UPDATE Production.Product  
  7.  SET Color = 'b'  
  8. WHERE Color = 'Black';  
  9.   
  10. -- simple logic to test  
  11. IF @@ROWCOUNT > 10  
  12. BEGIN  
  13.   
  14.  ROLLBACK WORK;  
  15.  PRINT 'transaction rolled back';  
  16. END  
  17. ELSE  
  18. BEGIN  
  19.    
  20.  COMMIT WORK;  
  21.  PRINT 'transaction committed.';  
  22. END  

No comments: