Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server printf

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 write it in a varchar, because my ERP won't let me handle the error messages.

This is SQL Server 2000.

Actual working example with RAISERROR:

declare @name varchar(10)
set @name = 'George'

RAISERROR ('Hello %s.', 10, 1, 'George')

prints Hello George

What I'm looking for:

declare @name varchar(10), @message varchar(50)
set @name = 'George'

SET @message = printf('Hello %s.', 'George')
return @message

This would return Hello George

like image 857
DonkeyMaster Avatar asked Feb 28 '11 10:02

DonkeyMaster


People also ask

What is printf in SQL?

"printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (lexing aka. parsing).

Is there a print command in SQL?

Usually, we use the SQL PRINT statement to print corresponding messages or track the variable values while query progress. We also use interactions or multiple loops in a query with a while or for a loop. We can also use the SQL PRINT statement to track the iteration.


1 Answers

PRINT is just RAISERROR with a severity of 0. So you can use.

declare @name varchar(10)
set @name = 'George'

RAISERROR ('Hello %s.', 0, 1, 'George') WITH NOWAIT

Edit to store it into a variable you can use the xp_sprintf extended stored procedure.

declare @name varchar(10)
set @name = 'George'

DECLARE @ret varchar(500)
exec master..xp_sprintf @ret OUTPUT, 'Hello %s.', @name
PRINT @ret
like image 91
Martin Smith Avatar answered Oct 05 '22 10:10

Martin Smith