如何在 SQL raiserror 中使用变量

How to use variables in SQL raiserror

我正在尝试在 raiserror @MaxAmount@MinAmount

中显示我的 int 变量
Raiserror('Total Amount should be less than %s and Greater than %s',16,1,@MaxAmount,@MinAmount)

但是我收到错误:

Must declare the scalar variable "@MaxAmount".

我想你可以这样试试:

DECLARE @MaxAmount int = 16;
DECLARE @MinAmount int = 1;

Raiserror('Total Amount should be less than %d and Greater than %d',@MaxAmount,@MinAmount)

如果您想了解有关 RAISERROR 的更多信息,go here

您需要将 %I 用于整数,如前所述,在使用前声明变量。

declare @MaxAmount int, @MinAmount int
select @MaxAmount = 50, @MinAmount = 5
Raiserror('Total Amount should be less than %i and Greater than %i',16,1,@MaxAmount,@MinAmount)

%s 用于 varchar 并且您的变量类型为 int 因此您需要尝试使用正确的格式说明符,即 %d

DECLARE @MaxAmount int = 16;
DECLARE @minAmount int = 1;
Raiserror('Total Amount should be less than %d and Greater than %d',@MaxAmount,@MinAmount)

查看 RAISEERROR 了解详情。

以上解决方案对我不起作用,因为您还必须声明严重性和状态。没有它,结果将是这样的:

Total Amount should be less than (null) and Greater than (null)

你可以试试这个:

DECLARE @MaxAmount int = 16;
DECLARE @MinAmount int = 1;

Raiserror('Total Amount should be less than %d and Greater than %d', 16, 1, @MaxAmount, @MinAmount)