Jan 05
SQL Server 2005 error handling
Over time, I’ve had the need for more and more robust error handling in SQL. Initially I accomplished this with transactions, but eventually I needed something more. Finally, I came up with a template that I have started to use every time I start writing a new SQL file.
BEGIN TRANSACTION-- DROP TEMP TABLESIF OBJECT_ID('tempdb..#my_temp_table') IS NOT NULLDROP TABLE #my_temp_table;BEGIN TRY-- LOGIC GOES HEREEND TRYBEGIN CATCHSELECTERROR_NUMBER() AS ErrorNumber,ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,ERROR_PROCEDURE() AS ErrorProcedure,ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage;END CATCH-- Error handling to ensure that transactions are appropriately rolled back on error-- and not left hangingSELECT @error_code = @@ERRORIF (@error_code <> 0) GOTO ERR_HANDLER-- CHANGE THIS TO COMMIT ON DEPLOYMENTROLLBACK TRANSACTIONGOTO THE_ENDERR_HANDLER:IF (@error_code <> 0) BEGINSELECT 'Unexpected errors occurred!'ROLLBACK TRANSACTIONENDTHE_END:- Download this code: sampleerrors.sql

January 5th, 2008 at 3:58 pm
You should make a template for yourself in SQL Server Management Studio: http://technet.microsoft.com/en-us/library/ms179334.aspx. That should save even more time.
February 20th, 2008 at 8:21 am
If only I could figure out how to get something similar to this working in PostgreSQL I’d be all set.