Try/Catch for SQL!?

March 5, 2009 by mrdavidlaing · Leave a Comment
Filed under: HOWTO, MSSQL 

Thanks to Nick Sertis for this trick – who knew TSQL could do try/catch statements!

Very useful when you need to write data manipulation scripts for production databases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
BEGIN TRY
 
    BEGIN TRAN
 
        --Some SQL
 
 
    COMMIT TRAN
 
END TRY
-- Catch the errors on the inserts
BEGIN CATCH
 
    ROLLBACK TRAN
    SELECT ERROR_MESSAGE()
 
END CATCH

  • Tags

  • Latest del.icio.us links