Apologies if this is not suitable, but really this is a 'why' rather than a 'how'. Not sure that is suitable, but don't know a better place to ask and I can't think how to phrase a google to get what I am looking for.
IF 'hell' = 'freezing over'
BEGIN
SELECT log(0)
END
Look at that statement. There is no world in which the IF clause will be true. If I attempt to run it I am expecting SQL to jump past the IF clause and move to the end. Instead I get:
An invalid floating point operation occurred.
This is bizarre. So I guess that is just the way that SQL does it's thing. Except...
IF 'hell' = 'freezing over'
BEGIN
SELECT 1/0
END
There is no error here. The statement in the IF clause should still generate an error. Could anyone explain why this is not happening?
This came up whilst debuggging a massive set of SQL calcs where EXP(SUM(LOG())) is used to accumulate data within an if clause. I can alter the code to stop that happening again, but why is it evaluating something within an IF clause that is not met.
Cheers.
EDIT: Additional amusement. Try catch? Pffft
IF 1=2
BEGIN
BEGIN TRY
SELECT SQRT(-1)
END TRY
BEGIN CATCH
END CATCH
END
Non mathematical:
IF 1=2
BEGIN
SELECT SUBSTRING('hello',-1,-1)
END
My guess would be that log(0)
is effectively evaluated prematurely due to constant-folding whereas 1/0
is not, either due to its cardinality estimation or more likely the fact that the ANSI_WARNINGS setting will affect the desired result of a divide by zero (overflow vs NULL).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With