recently when we have migrated to SQL Server 2012, we have seen a change in how it evaluate the logical expression in the having clause .
I created a simple query that allows you to see the problem :
SELECT sum (0)
HAVING sum (0) > 0 AND 1/sum (0)> 0
The objective is to test the value of a division . Obviously , before any division , it is necessary to check whether the divisor is not equal to 0, that is what I do with sum ( 0 )> 0 . Except that , it generates the following error:
Msg 8134 , Level 16 , State 1 , Line 1 Division by zero.
SQL Server has evaluated all expressions , even if the first is wrong . In our previous SQL Server 2000 version, this worked well. On the other hand , a similar test in the WHERE clause does not generate an error.
The problem can be reproduced with other conditions such as:
select ISNUMERIC(num)
from (select '12J' as num) t
group by num
having ISNUMERIC(num)=1
and max(cast(num as int)) >0
Which generates : Server : Msg 245, Level 16 , State 1 , Line 1 Failed to convert the varchar value '12J ' to data type int .
Question: is this normal? is there a way to tell it not to evaluate other expressions if the first is false ?
Thank you for your insights !