【问题标题】:Sql server divide by zero issue [closed]Sql server除以零问题[关闭]
【发布时间】:2012-12-06 20:32:59
【问题描述】:

请有人帮我解决这个问题: 我有这个选择:

SELECT Cast(( Isnull(price, 0) + Isnull(notarycosts, 0)
              + Isnull(landtax, 0) + Isnull(othertaxes, 0)
              + Isnull(agentfee, 0) + Isnull(cadastralfee, 0)
              + Isnull(tabulationfee, 0)
              + Isnull(certsarcini, 0) ) / ( totalareasqm / 10000 * fixhist ) AS
                   DECIMAL(12, 4)) AS EurPerHa

有时我得到一个除以零的错误,我的应用程序被阻止,直到我从数据库中删除最后一行。 我能以某种方式解决这个问题吗?

谢谢!

【问题讨论】:

  • 除以零来自 totalareasqm 或 fixhist = 0 所以添加一个 WHERE 在您的查询中检查它
  • 我会尝试对错误进行简单的谷歌搜索,然后将其作为问题发布在这里。
  • A quick search 除以零)返回了一堆线程,这些线程可能会在更短的时间内回答这个问题;-)

标签: sql sql-server database sql-server-2008 tsql


【解决方案1】:

TotalAreaSqmFixHist 为 0。由于我们不能除以零,当存在零时,您的脚本应该怎么做?

我通常会看到将其设为 NULL 或使用已知值使其工作的方法。我不知道安全值是多少。

使其为空方法

select cast((isnull(price,0)+isnull(notarycosts,0)+isnull(landtax,0)+isnull(othertaxes,0)+isnull(agentfee,0)+isnull(cadastralfee,0)+isnull(tabulationfee,0)+isnull(certsarcini,0))/(NULLIF(TotalAreaSqm, 0)/10000*NULLIF(FixHist, 0) as decimal(12,4)) as EurPerHa

【讨论】:

    【解决方案2】:

    检查不为空且不为 0 的 FixHistTotalAreaSqm

    代码:

    select CASE WHEN ISNULL(NULLIF(FixHist,0),0) !=0 
                     AND ISNULL(NULLIF(TotalAreaSqm,0),0) !=0
    THEN
    cast((isnull(price,0)+
    isnull(notarycosts,0)+
    isnull(landtax,0)+
    isnull(othertaxes,0)+
    isnull(agentfee,0)+
    isnull(cadastralfee,0)+
    isnull(tabulationfee,0)+
    isnull(certsarcini,0))/(TotalAreaSqm/10000*FixHist) as decimal(12,4))
    ELSE 0 END as EurPerHa
    

    【讨论】:

    • 不完整,TotalAreaSqm 也可以为零
    【解决方案3】:
    SELECT IIF( TotalAreaSqm*FixHist=0
                ,null
                , cast(
                        ( isnull(price,0)
                          + isnull(notarycosts,0)
                          + isnull(landtax,0)
                          + isnull(othertaxes,0)
                          + isnull(agentfee,0)
                          + isnull(cadastralfee,0)
                          + isnull(tabulationfee,0)
                          + isnull(certsarcini,0) 
                        )
                        /
                       (TotalAreaSqm / 10000 * FixHist ) 
                   as decimal(12,4))
               ) as EurPerHa
    

    【讨论】:

      【解决方案4】:
      ( isnull(totalareasqm,1) / 10000 * isnull(fixhist,1) )
      

      【讨论】:

      • 处理 NULL 值,而不是除数为零时...
      • 是的,完全忘记了,谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2012-01-29
      相关资源
      最近更新 更多