Microsoft has introduced a construct to handle errors in SQL Server that is ‘TRY – CATCH’. It is similar to .NET ‘Try – Catch’ block for handling the exceptions. When an error is caught in a T-SQL statement which is inside the ‘TRY’ block, the control is automatically transferred to the ‘CATCH’ block.
We can then process the error in the ‘CATCH’ block.So let’s see below syntax of the TRY CATCH block for handling the errors in SQL Server.
BEGIN TRY
//SQL QUERY
END TRY
BEGIN CATCH
SELECT
//Some in-build error functions
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;
END CATCH
We can then process the error in the ‘CATCH’ block.So let’s see below syntax of the TRY CATCH block for handling the errors in SQL Server.
BEGIN TRY
//SQL QUERY
END TRY
BEGIN CATCH
SELECT
//Some in-build error functions
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;
END CATCH