Skip to content
Advertisement

Throw exception from SQL Server function to stored procedure

I have stored procedure in SQL Server 2012 say spXample and a scaler-valued function say fXample. I call a function fXample from spXample. Can I throw an exception in function and catch it in stored procedure’s Catch block and rethrow to the calling C# code?

Update:

The function I wrote like:

I am getting error

Msg 443, Level 16, State 14, Procedure fXample, Line 46 Invalid use of a side-effecting operator ‘THROW’ within a function.

How do I write alternative code to achieve above functionality?

Advertisement

Answer

You can do this by forcing an error condition when your validation fails, provided that isn’t a possible error that might occur naturally. When you know a certain error can only occur when validation has failed, you can handle that in a custom way by checking for that error_number in your catch block. Example in tempdb:

Now try it out:

Results:

Msg 50001, Level 16, State 1, Procedure spXample, Line 12
Your custom error message.

Msg 220, Level 16, State 2, Procedure spXample, Line 7
Arithmetic overflow error for data type tinyint, value = 256.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement