MSSQL
[MSSQL] TRY / CATCH 사용방법
평생업
2016. 7. 3. 00:09
USE AdventureWorks2008R2; GO -- Variable to store ErrorLogID value of the row -- inserted in the ErrorLog table by uspLogError DECLARE @ErrorLogID INT; 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 operation succeeds, commit the transaction. COMMIT TRANSACTION; END TRY BEGIN CATCH -- Call procedure to print error information. EXECUTE dbo.uspPrintError; -- Roll back any active or uncommittable transactions before -- inserting information in the ErrorLog.
-- XACT_STATE = 0 means there is no transaction and
-- a commit or rollback operation would generate an error.IF XACT_STATE() <> 0 BEGIN ROLLBACK TRANSACTION; END EXECUTE dbo.uspLogError @ErrorLogID = @ErrorLogID OUTPUT; END CATCH; -- Retrieve logged error information. SELECT * FROM dbo.ErrorLog WHERE ErrorLogID = @ErrorLogID; GO