【问题标题】:Divide by zero error encountered while running a query运行查询时遇到除以零错误
【发布时间】:2020-11-12 18:10:41
【问题描述】:

以下是我尝试使用 Microsoft SQL Server Management Studio 运行的查询:

update [SG report MPD-4153] 
set [percent_paid] =  (try_convert(float, [Savings This Season])  * 100 / try_convert(float, [Savings 
Goal Amount]));

【问题讨论】:

  • 错误在这里告诉你问题所在,错误不明白怎么办?
  • 将分母包装在 NULLIF() 中,即 NULLIF( expr , 0 )
  • 另外,您的以Goal Amount结尾的列真的的名称中有换行符吗?

标签: sql sql-server ssms


【解决方案1】:

你可以在分母上使用nullif()

update [SG report MPD-4153] 
    set [percent_paid] =  (try_convert(float, [Savings This Season])  * 100 
                           nullif(try_convert(float, [Savings Goal Amount], 0)
                          );

【讨论】:

    【解决方案2】:

    我假设 [Savings Goal Amount] 有时可以为 0。在这种情况下,您必须确定您希望将 [percent_paid] 设置为什么。假设在这种情况下您可以将其设置为 NULL,您可以这样做

    update [SG report MPD-4153] 
       set [percent_paid] =  case when try_convert(float, [Savings Goal Amount] = 0 
                                  then null
                                  else (try_convert(float, [Savings This Season])  * 100 /
                                          try_convert(float, [Savings Goal Amount]))
                               end;
    

    如果您想要NULL 以外的内容,或者更改then 子句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      相关资源
      最近更新 更多