SQL中

时间:2017-02-28 10:51:50

标签: sql sql-server

我有这个问题:

-- There are a select and joins in the query
--Then I have this Where part
WHERE
(
    dbo.Table.Furnished IS NULL
    OR dbo.Table.Furnished = 0
)
AND (
    dbo.Table.Type2 = N'House'
)
AND (
    dbo.Table.Type3 = N'ForSale'
)
AND (
    dbo.Table.FixedArea/ dbo.Table.ToiletNumber< 250
)
AND (
    dbo.Table.FixedArea> 25
)

AND (
    CASE
    WHEN dbo.Table.Segment1 = 1 THEN
        'FirstGroup'
    WHEN dbo.Table.Segment1 = 2 THEN
        'SecondGroup'
    WHEN dbo.Table.Segment1 = 3 THEN
        'ThirdGroup'
    ELSE
        'Undefined'
    END <> 'Undefined'
)
AND (
    dbo.Table.Segment2 <> N'Undefined'
)
OR 
(
    dbo.Table.Furnished IS NULL
    OR dbo.Table.Furnished = 0
)
AND (
    dbo.Table.Type2 = N'Commercial'
)
AND (
    dbo.Table.Type3 = N'ForSale'
)
AND (
    dbo.Table.FixedArea/ dbo.Table.ToiletNumber< 250
)
AND (
    dbo.Table.FixedArea> 25
)

AND (
    CASE
    WHEN dbo.Table.Segment1 = 1 THEN
        'FirstGroup'
    WHEN dbo.Table.Segment1 = 2 THEN
        'SecondGroup'
    WHEN dbo.Table.Segment1 = 3 THEN
        'ThirdGroup'
    ELSE
        'Undefined'
    END <> 'Undefined'
)
AND (
    dbo.Table.Segment2 <> N'Undefined'
)

当我在原始查询的底部添加此部分时(没有任何分区或类似内容),我得到Divide by zero error encountered.

OR
    (
        dbo.Table.Geo IS NOT NULL
    )
AND (
    dbo.Table.FixedArea > 0
)
AND (
    dbo.Table.Price > 0
)
AND (
    dbo.Table.RoomNumber LIKE N'%+%'
)
AND (
    dbo.Table.Furnished IS NULL
    OR dbo.Table.Furnished = 0
)
AND(
dbo.Table.Type3 = N'ForRent'
)

为什么我会将此除以零误差?我没有添加任何部门。我只是添加了一些新的过滤器。请帮我解决这个错误。感谢。

2 个答案:

答案 0 :(得分:4)

你实际上在这里做dbo.Table.FixedArea/ dbo.Table.ToiletNumber< 250 ...而且可能ToiletNumber为零

编辑:尝试通过将上述代码更改为

来重新运行查询
dbo.Table.FixedArea / NULLIF(dbo.Table.ToiletNumber, 0) < 250

答案 1 :(得分:1)

你div / 0在这里:

 (
    dbo.Table.FixedArea/ dbo.Table.ToiletNumber < 250
)

此:

AND (
    dbo.Table.FixedArea> 25
)

可能删除任何div / 0

现在这个:

AND (
    dbo.Table.FixedArea > 0
)

意味着FixedArea在0到25之间的行可能对于ToiletNumber而言为0,并且必须进行评估

修复:

case when ToiletNumber = 0 then 1
     else dbo.Table.FixedArea/ dbo.Table.ToiletNumber
end <250