sql server除以零错误

时间:2013-03-23 00:59:47

标签: sql-server

任何方式我都有以下表格的查询

select 
(select count(*) from sometable where somecritiea) / ((select count(*) from sometable where somecritiea) + 0.000001) 
from sometable

我将计数结果除以计数结果,因此空值不是问题。

当我运行这个时,我得到一个“遇到零除错误”。注意除数中的+0.000001。

如果我在一个新表中插入枚举器(?)和除数,然后执行相同的计算,它将按预期工作。

select 
(select count(*) from sometable where somecritiea) a/ ((select count(*) from sometable where somecritiea) + 0.000001) b
into testtable
from sometable

从testtable中选择a / b

这会返回预期的结果而没有错误。

如果我跑

select * from testtable where b = 0
i get 0 records as expected.

我真的在这里失去了它,这是一个5分钟的工作,已经变成了5个小时的混乱。

我也试过

select *
((select count(*) from sometable where somecritiea) + 0.000001) divisor
from sometable
where divisor = 0

这不会返回任何记录。

3 个答案:

答案 0 :(得分:3)

老实说,我也无法重现你的问题,但无论如何都应该有效。

WITH Divisor AS (select count(*)*1.0 BotCnt from sys.procedures),
    Dividend AS (select count(*)*1.0 TopCnt from sys.tables )
SELECT 
    CASE WHEN BotCnt = 0 THEN 0 ELSE TopCnt/BotCnt END,
    *
FROM sys.objects
CROSS JOIN Divisor
CROSS JOIN Dividend

请注意*1.0。那就是将计数转换为小数。您可以轻松地使用显式转换。 CROSS JOIN仅起作用,因为两个CTE是单行。否则使用带有ON子句的INNER JOIN。

答案 1 :(得分:1)

这是我能够快速复制你的场景的最接近的,它运行正常;返回0.0000000:

with sometable as (
  select * from ( values 
    (0)
  ) sometable(value)
)
select 
  (select count(*) from sometable where value <> 0 )
/ 
( (select count(*) from sometable where value <> 0 ) + 0.000001 ) 
from sometable

答案 2 :(得分:0)

在你的除数上试试NULLIF

select 
(select count(*) from sometable where somecritiea) / NULLIF((select count(*) from sometable     where somecritiea) + 0.000001), 0) from sometable

如果分母为0,这将返回NULL而不是除以0。如果您不想要NULL但需要其他默认答案(例如9),请在整个查询中使用ISNULL将其转换回0。