RAISERROR - formatting the error string

Starting with SQL 2008, RAISERROR has supported 'variable substitution' The article explains how to format an error message that contains variables.

Our mandate is not to supply technically correct, in-depth articles on how things work. We're about quick code examples that you can read and get back to work.

Personally, when I want something explained in depth I'll search msdn or ask Pinal Dave <smiles>

How to format strings, integers, floating point numbers, and strings in RAISERROR:

Note the RAISERROR function does not support all variable types, DATEs and NUMERICs have to be converted. Also that we added the step of wrapping the @var variable with quotes to make it format prettier, we used STR to convert a NUMERIC value to VARCHAR(10) but you still have to LTRIM it.

Declare @var varchar(10)
Declare @int as int
Declare @num as varchar(10)
Declare @dt as varchar(10)
 
select
    @var = quotename('table',char(39)),
    @int = 15,
    @num = ltrim(str(5.12,10,2)),
    @dt = convert(varchar(10),getdate(),101)
 
 
raiserror('Error, %s is a varchar, %d is integer, %s is numeric, %s is a date ',16,2,@var,@int,@num,@dt)

This will return this message:


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences