Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I put error handling in T-SQL?

As a developer, error handling and try/catch is a very important part of the code I write.

However, in SQL Server Stored Procs, is it best practise to write error handling within the SP? And if one does not (which seems to be the common case), does the exception propagate to the .NET code? I ask that question as I am under the impression that T-SQL behaves like C# error handling.

And what is the best way to write error handling in T-SQL?

like image 791
GurdeepS Avatar asked May 20 '26 22:05

GurdeepS


1 Answers

Yes, use TRY...CATCH in your TSQL code. The exception does NOT propogate up to the client in this case.

Propogation will occur whenever you use RAISEERROR or on unhandled SQL exceptions.

BEGIN TRY
     SELECT Foo FROM MyLinkedServer.dbo.SomeTable; --what if the remote server is down?

     DECLARE @Baz uniqueidentifier  = 15/2; --oops        
END TRY
BEGIN CATCH
    SELECT @Baz = NEWID();
    ROLLBACK TRAN; 
    --whatever business logic you have for handling your exception.
END CATCH
like image 57
p.campbell Avatar answered May 22 '26 11:05

p.campbell