【问题标题】:How to use variables in SQL raiserror如何在 SQL raiseerror 中使用变量
【发布时间】:2015-09-16 10:03:22
【问题描述】:

我正在尝试在 raiserror @MaxAmount@MinAmount 中显示我的 int 变量

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

但我收到错误:

必须声明标量变量“@MaxAmount”。

【问题讨论】:

  • 它是基本的,你必须在查询中使用它之前声明变量。
  • 我确实声明了,但是当我在 raiserror 中使用它时出现了拼写错误。解决了!

标签: sql sql-server raiserror


【解决方案1】:

%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

【讨论】:

  • 这对我不起作用,我必须根据@Edward Comeau 的回答另外提供严重性和状态参数,然后是最大/最小数量参数,否则消息是:Total Amount should be less than (null) and Greater than (null)
【解决方案2】:

您需要将 %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)

【讨论】:

    【解决方案3】:

    我认为你可以这样尝试:

    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

    【讨论】:

      【解决方案4】:

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

      总金额应小于(null)且大于(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)
      

      【讨论】:

      • 感谢您承认以前的答案并强调您的答案与他们的不同之处。这在用已确定的答案回答旧问题时特别有用,就像在这种情况下一样。也就是说,@Edward-Comeau 五年前的回答确实包括严重程度和状态。
      猜你喜欢
      • 1970-01-01
      • 2015-07-21
      • 2013-02-25
      • 2014-07-13
      • 1970-01-01
      • 2013-11-16
      • 2011-08-04
      • 2021-03-09
      • 2011-02-10
      相关资源
      最近更新 更多