How to report an error from a SQL Server user-defined function How to report an error from a SQL Server user-defined function sql-server sql-server

How to report an error from a SQL Server user-defined function


You can use CAST to throw meaningful error:

create function dbo.throwError()returns nvarchar(max)asbegin    return cast('Error happened here.' as int);end

Then Sql Server will show some help information:

Msg 245, Level 16, State 1, Line 1Conversion failed when converting the varchar value 'Error happened here.' to data type int.


The usual trick is to force a divide by 0. This will raise an error and interrupt the current statement that is evaluating the function. If the developer or support person knows about this behavior, investigating and troubleshooting the problem is fairly easy as the division by 0 error is understood as a symptom of a different, unrelated problem.

As bad as this looks from any point of view, unfortunately the design of SQL functions at the moment allows no better choice. Using RAISERROR should absolutely be allowed in functions.


Following on from Vladimir Korolev's answer, the idiom to conditionally throw an error is

CREATE FUNCTION [dbo].[Throw](    @error NVARCHAR(MAX))RETURNS BITASBEGIN    RETURN CAST(@error AS INT)ENDGODECLARE @error NVARCHAR(MAX)DECLARE @bit BITIF `error condition` SET @error = 'My Error'ELSE SET @error = '0'SET @bit = [dbo].[Throw](@error)