Pete Freitag Pete Freitag

Try Catch for SQLServer T-SQL

Published on April 07, 2008
By Pete Freitag
databases

Error handling in SQL Server T-SQL scripts is not always the most graceful thing to deal with. With the release of Microsoft SQL Server 2005 you can now use TRY / CATCH statements. Here's a simple example of try / catch on sqlserver:

BEGIN TRY
	-- try / catch requires SQLServer 2005 
	-- run your code here
END TRY
BEGIN CATCH
	PRINT 'Error Number: ' + str(error_number()) 
	PRINT 'Line Number: ' + str(error_line())
	PRINT error_message()
	-- handle error condition
END CATCH

If you want to throw an exception with SQL Server you can use the RAISERROR() function, for example:

RAISERROR('Error Message', 18, 0);


sql sqlserver microsoft 2005 errors

Try Catch for SQLServer T-SQL was first published on April 07, 2008.

If you like reading about sql, sqlserver, microsoft, 2005, or errors then you might also like:

Discuss / Follow me on Twitter ↯