SQL Server printf

Don*_*ter 13 sql-server sql-server-2000

在Sql Server中是否有类似printf的功能?我想要与RAISERROR函数相同的功能,但我不想抛出错误或打印消息,而是想在varchar中编写它,因为我的ERP不会让我处理错误消息.

这是SQL Server 2000.

RAISERROR的实际工作示例:

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

RAISERROR ('Hello %s.', 10, 1, 'George')
Run Code Online (Sandbox Code Playgroud)

版画 Hello George

我在找什么:

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

SET @message = printf('Hello %s.', 'George')
return @message
Run Code Online (Sandbox Code Playgroud)

这会回来 Hello George

Mar*_*ith 15

PRINT只是RAISERROR严重性为0.所以你可以使用.

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

RAISERROR ('Hello %s.', 0, 1, 'George') WITH NOWAIT
Run Code Online (Sandbox Code Playgroud)

编辑将其存储到变量中,您可以使用xp_sprintf扩展存储过程.

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

DECLARE @ret varchar(500)
exec master..xp_sprintf @ret OUTPUT, 'Hello %s.', @name
PRINT @ret
Run Code Online (Sandbox Code Playgroud)


Dam*_*ver 10

如果您具有有限数量的格式字符串,并且能够将它们添加到sysmessages(通过sp_addmessage),则可以使用FORMATMESSAGE:

与RAISERROR语句一样,FORMATMESSAGE通过将所提供的参数值替换为消息中的占位符变量来编辑消息.有关错误消息中允许的占位符和编辑过程的详细信息,请参阅RAISERROR.


以下是SQL Server 2005或更高版本的有效答案,但不幸的是,OP正在寻求SQL Server 2000的解决方案:


它太丑了,滥用了Try/Catch并且RAISERROR:

declare @message varchar(50)

begin try
    RAISERROR('Hello %s',16,1,'george')
end try
begin catch
    set @message = ERROR_MESSAGE()
end catch

print @message
Run Code Online (Sandbox Code Playgroud)


Ian*_*emp 6

从 SQL Server 2016 开始formatmessageraiserror进行了扩展,使它们几乎可以像 C 函数一样工作printf。第一个参数(以前必须是引用 中预定义消息的整数sys.messages)现在可以是printf-style 格式字符串:

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
*/
Run Code Online (Sandbox Code Playgroud)

虽然throw 不隐式支持相同的格式,但没有什么可以阻止您与此构造一起使用formatmessage

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
*/
Run Code Online (Sandbox Code Playgroud)