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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With