I am trying to put a try-catch statement inside a trigger using Microsoft Server 2005.
BEGIN TRANSACTION
BEGIN TRY
--Some More SQL
COMMIT TRANSACTION
To avoid losing the transactional data prior to the trigger action, you'll want to call COMMIT TRAN. Do this before the TRY/CATCH block and you will get your desired results.
Example:
COMMIT TRAN
BEGIN TRY
-- possible error occurs here...
END TRY
BEGIN CATCH
PRINT 'Error on line ' + CAST(ERROR_LINE() AS VARCHAR(10))
PRINT ERROR_MESSAGE()
END CATCH
It will throw the following error still - not sure how to avoid:
The transaction ended in the trigger. The batch has been aborted.
But both the original transaction and the trigger transaction should commit successfully.
UPDATE: To avoid the exception last error, call BEGIN TRAN within the TRY statement. Note, Microsoft recommends to NOT call COMMIT TRAN within a trigger, but if unavoidable, this should work for you.
Example:
COMMIT TRAN
BEGIN TRY
BEGIN TRAN