【问题标题】:How to avoid divide by zero error here?如何在这里避免除以零错误?
【发布时间】:2012-07-05 02:39:32
【问题描述】:

我的以下查询遇到除以 0 错误:

select  pp.building_name, 
        ld.tenant_trading_name,  
        tenancy_reference,  
        ld.turnover_threshold, 
        ld.percentage_rent, 
        ld.income_base_rent_ach, 
        ld.income_base_rent_ach / ld.percentage_rent as correct 
from 
    lease_deal.lease ld

inner join property.property pp
    on ld.building_id = pp.building_id

where 
    (ld.income_base_rent_ach / ld.percentage_rent ) <> ld.turnover_threshold
    and lease_status = 'APPROVED'
    and ld.progenesis_load_date is  null
order by pp.building_name

我已尝试通过执行以下操作来纠正此问题 - 但我收到语法错误并且我不确定为什么?这里有什么语法错误?

select  pp.building_name, 
        ld.tenant_trading_name,  
        tenancy_reference,  
        ld.turnover_threshold, 
        ld.percentage_rent, 
        ld.income_base_rent_ach, 
        ld.income_base_rent_ach / ld.percentage_rent as correct 
from 
    lease_deal.lease ld

inner join property.property pp
    on ld.building_id = pp.building_id

where 
    case when ld.percentage_rent = 0
    then 1=1
    else ((ld.income_base_rent_ach / ld.percentage_rent ) <> ld.turnover_threshold)
    end
    and lease_status = 'APPROVED'
    and ld.progenesis_load_date is  null
order by pp.building_name

【问题讨论】:

    标签: sql sql-server sql-server-2008 tsql divide-by-zero


    【解决方案1】:

    换一个怎么样

    (ld.income_base_rent_ach / ld.percentage_rent ) <> ld.turnover_threshold
    

    ld.income_base_rent_ach <> (ld.percentage_rent * ld.turnover_threshold)
    

    【讨论】:

    • 优秀。关于为什么我也收到语法错误的任何想法(教育好奇心)
    • 你被零除。道格通过将其更改为乘法(其中零没问题)消除了这种可能性。我的回答是尝试合理地检查 0 并使用惰性求值来确保它永远不会被零除。
    • 澄清一下:你不能依赖惰性求值或短路,因为你永远无法确定给定x or y SQL Server 将首先求值x - 请参阅this post例如,由于这件事,短路不起作用:SQL Server 不对从左到右的评估做出任何保证,即使在文档确实的情况下(没有双关语)让您相信此保证存在。
    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 2010-10-26
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多