如何避免除以零错误

时间:2012-12-06 10:44:53

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

  

可能重复:
  How to avoid the “divide by zero” error in SQL?

我有一个关于Sql Server除以零错误的问题。 有时这个错误和视图被阻止,直到我删除相应的行。 你能帮帮我,给我一些建议,我怎么能避免这个? 感谢。

CREATE VIEW Acq
AS
SELECT
        ac_id
       ,[Company]
       ,No
       ,[ContractID]
       ,[Seller]
       ,[AcquistionDate]
       ,[Village]
       ,[Commune]
       ,[Area]
       ,[PlotArea]
       ,[FieldNo]
       ,[Topo1]
       ,[Topo2]
       ,[Topo3]
       ,[Topo4]
       ,[Topo5]
       ,[TotalAreaSqm]
       ,[OwnershipTitle]
       ,[CadastralNO]
       ,[Type]
       ,[Price]
       ,[NotaryCosts]
       ,[LandTax]
       ,[OtherTaxes]
       ,[AgentFee]
       ,[CadastralFee]
       ,[TabulationFee]
       ,[CertSarcini]
       ,[ProcuraNO]
       ,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)) as decimal(12,4)) as TotalCosts
       ,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) as decimal(12,4)) as RonPerHa
       ,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
       ,[DeclImpunere]
       ,[FixHist]
       ,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))/FixHist as decimal(12,4)) as EurHist
       ,[LandStatus]


FROM      tblAcq

2 个答案:

答案 0 :(得分:4)

(TotalAreaSqm/10000)等表达式替换为(nullif(TotalAreaSqm,0)/10000)

这假设您希望在除以零的情况下结果为null。有关nullif的说明,请参阅文档here

答案 1 :(得分:1)

CASE (TotalAreaSQM/1000 <> 0) THEN 'do work' ELSE 'dont do it and pass the 0 or what ever'
你可以写下类似的东西。