Is there a printf-like function in Sql Server? I want the same features as the RAISERROR function, but instead of throwing an error, or printing a message, I want to wri
As of SQL Server 2016, formatmessage and raiserror have been extended to allow them to work almost exactly like C's printf
function. The first argument (that previously had to be an integer referring to a predefined message in sys.messages
) can now be a printf
-style format string:
select formatmessage(
'This is a string %s and this is an integer %i%sand this is a string weirdly padded with spaces <<%7.3s>>%sand this is a hex representation of an integer %x',
'foo',
42,
char(13) + char(10),
'bar',
char(13) + char(10),
1337
);
/* output:
This is a string foo and this is an integer 42
and this is a string weirdly padded with spaces << bar>>
and this is a hex representation of an integer 539
*/
While throw
does not implicitly support this same formatting, there is nothing stopping you from using formatmessage together with this construct:
declare @errorMessage nvarchar(max) = formatmessage(
'This is a string %s and this is an integer %i%sand this is a string weirdly padded with spaces <<%7.3s>>%sand this is a hex representation of an integer %x',
'foo',
42,
char(13) + char(10),
'bar',
char(13) + char(10),
1337
);
throw 50000, @errorMessage, 1;
/* output:
Msg 50000, Level 16, State 1, Line 21
This is a string foo and this is an integer 42
and this is a string weirdly padded with spaces << bar>>
and this is a hex representation of an integer 539
*/