• Hugo Kornelis (12/23/2012)


    While hunting for this information, I did find a few Connect items about errors with WHEN (something that's never true) THEN MIN(1/0) or WHEN (something that's always true) THEN 1 ELSE MIN(1/0) - they are the connect items that prompted this clarification to be added to Books Online.

    I think this more a theoretical problem though.

    SQL Server seems short-cirquit constant expressions (1/0) first, but usually you wont have such an expression in your queries (unless generated by code).

    Example: The version with 1/0 returns the error, but the semantically identical version with 1/(x-x) does not return the error:

    SELECT CASE WHEN object_id = object_id+1 THEN MIN(1/0) ELSE 1 END

    FROM sys.objects GROUP BY object_id

    -----------

    Msg 8134, Level 16, State 1, Line 1

    Divide by zero error encountered.

    SELECT CASE WHEN object_id = object_id+1 THEN MIN(1/(object_id-object_id)) ELSE 1 END

    FROM sys.objects GROUP BY object_id

    ...

    (1456 row(s) affected)

    And we can even short-cirquit version 1 once more to make it work again:

    SELECT CASE WHEN 1<>1 THEN MIN(1/0) ELSE 1 END FROM sys.objects GROUP BY object_id

    ...

    (1456 row(s) affected)

    SQL Server knows that 1<>1 is never true, and therefore doesn't bother to evaluate MIN(1/0)

    Best Regards,

    Chris Büttner