Search code examples
sql-serverstored-proceduresthrow

Throwing errors - The correct % formatting values in error message


I'm trying to throw a custom error from my stored procedure in SQL Server but am getting an error when compiling. The problem is clear. I am trying to display the value of a parameter of type bit and I believe my format statement is wrong. I have the following:

 EXEC sys.sp_addmessage  
   @msgnum   = 60000 
  ,@severity = 16
  ,@msgText  = N'Bad parameter. You cannot pass NULLs to this procedure, UseAlternateEquity (%i), AlternateEquity (%d), PushEmail (%i)'
                  ,@lang     = NULL;

declare @msg1 NVARCHAR(2048) = FORMATMESSAGE(60000, @UseAlternateEquity, @AlternateEquity, @PushEmail);
throw 60000, @msg1, 1;

The variables @UseAlternateEquityand @PushEmailare of type bit

Could someone tell me what the appropriate format type is please. I have searched high and low and can't find the answer


Solution

  • Just cast your @UseAlternateEquity and @PushEmail to another type prior to pass them. You can cast them to varchar or to int like this (I'm on the 2008 so I can RAISERROR)

        declare @UseAlternateEquityand bit = 1, 
                @PushEmailare bit = 0,
                @AlternateEquity bit = 1;
    
        declare @UseAlternateEquityand_1 int = @UseAlternateEquityand, 
                @PushEmailare_1 int = @PushEmailare,
                @AlternateEquity_1 int = @AlternateEquity;
    
        RAISERROR ( N'Bad parameter. You cannot pass NULLs to this procedure, UseAlternateEquity (%u), AlternateEquity (%u), PushEmail (%u)', 
                   16,  
                   1,  
                   @UseAlternateEquityand_1,  
                   @AlternateEquity_1,
                   @PushEmailare_1);