Created
October 1, 2016 17:40
-
-
Save ronascentes/ffcda39e6c70ca1a11f5f4997b33f86e to your computer and use it in GitHub Desktop.
Using TRY...CATCH in T-SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SET XACT_ABORT ON; | |
BEGIN TRY | |
BEGIN TRANSACTION; | |
-- A FOREIGN KEY constraint exists on this table. This | |
-- statement will generate a constraint violation error. | |
DELETE FROM Production.Product | |
WHERE ProductID = 980; | |
-- If the DELETE statement succeeds, commit the transaction. | |
COMMIT TRANSACTION; | |
END TRY | |
BEGIN CATCH | |
-- Execute error retrieval routine. | |
EXECUTE usp_GetErrorInfo; | |
-- Test XACT_STATE: | |
-- If 1, the transaction is committable. | |
-- If -1, the transaction is uncommittable and should | |
-- be rolled back. | |
-- XACT_STATE = 0 means that there is no transaction and | |
-- a commit or rollback operation would generate an error. | |
-- Test whether the transaction is uncommittable. | |
IF (XACT_STATE()) = -1 | |
BEGIN | |
N'The transaction is in an uncommittable state.' + | |
'Rolling back transaction.' | |
ROLLBACK TRANSACTION; | |
END; | |
-- Test whether the transaction is committable. | |
IF (XACT_STATE()) = 1 | |
BEGIN | |
N'The transaction is committable.' + | |
'Committing transaction.' | |
COMMIT TRANSACTION; | |
END; | |
END CATCH; | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment