Error Handling in User Defined Functions
I want to write a non-CLR user-defined function in SQL Server 2005. This function takes an input string and returns an output string. If the input string is invalid, then I want to indicate an error to the caller.
My first thought was to use RAISERROR to raise an exception. However, SQL Server does not allow this inside a UDF (though you can raise exceptions in CLR-based UDFs, go figure).
My last resort would be to return a NULL (or some other error-indicator value) from the function if the input value is in error. However, I don’t like this option, as it:
- Doesn’t provide any useful information to the caller
- Doesn’t allow me to return a NULL in response to valid input (since it’s used as an error code).
Is there any caller-friendly way to halt a function on an error in SQL Server?
2 Solutions collect form web for “Error Handling in User Defined Functions”
It seems that SQL Server UDF’s are a bit limited in this (and many other) way.
You really can’t do a whole lot about it – that’s (for now) just the way it is. Either you can define your UDF so that you can signal back an error condition by means of its return value (e.g. returning NULL in case of an error), or then you would almost have to resort to writing a stored procedure instead, which can have a lot more error handling and allows RAISERROR and so forth.
So either design your UDF to not require specific signaling of error conditions, or then you have to re-architect your approach to use stored procedures (which can have multiple OUTPUT parameters and thus can also return error code along with your data payload, if you need that), or managed CLR code for your UDF’s.
Sorry I don’t have a better idea – for now, I’m afraid, those are your options – take your pick.
There’s a possible solution given in an answer to a duplicate question here, based on this idea:
return cast('Error message here.' as int);
Which throws something like this:
Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value 'Error message here.' to data type int.
It works OK for scalar-valued UDFs, but not for table-valued ones.