2012-07-05 43 views
1

下面的查詢,我是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 

回答

3

如何與

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

優秀更換

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

。任何想法,爲什麼我得到的語法錯誤也(教育好奇心) – Codingo

+0

你除以零。 Doug通過將其改爲乘法(其中零不成問題)來消除了這種可能性。我的回答是試圖理智地檢查0並使用懶惰評估來確保它永遠不會被零除。 – Fosco

+0

只是爲了澄清:你不能依賴懶惰評估或短路,因爲你永遠不能確定給定'x或y'SQL Server首先會評估'x' - 請參閱[本文](http:///dba.stackexchange.com/questions/12941/does-sql-server-read-all-of-a-coalesce-function-even-if-the-first-argument-is-no)查看短路情況的例子因爲這件事情不起作用:即使在文檔*確實存在的情況下(無雙關語),SQL Server也不會對從左到右的評估做出任何保證。 –