select top 10 *, case
when datediff(day,DateOfSale, getDate()) > 5 then '5'
when datediff(day,DateOfSale, getDate()) > 10 then '10'
... (more datediff clauses)
...
...
else '20'
end as jack
from Foo
Is SQL Server smart enough to evaluate the datediff function call once within the case statement and then use that value for every when clause? Or is the function is getting called ‘n’ times, where ‘n’ is the amount of when clauses?
It’s hard to see how SQL Server could evaluate the call once. The call has a column as parameter and so has to be evaluated for every row.
Thus, your condition is better written like:
In this case the difference is small. Date calculations are cheap.
The classic example where the function call does matter is a
wherecondition on a table with an index on the date column. For example,YourTablewith an index on(dt). This query would allow an index to be used:While this query would not: