Aaron Bertrand blogs on an estimation failure with DATEADD and SYSDATETIME/SYSUTCDATETIME:
Essentially, the problem is that a poor estimate can be made not simply when
SYSDATETIME()
(orSYSUTCDATETIME()
) appears, as Erland originally reported, but when anydatetime2
expression is involved in the predicate (and perhaps only whenDATEADD()
is also used). And it can go both ways – if we swap>=
for<=
, the estimate becomes the whole table, so it seems that the optimizer is looking at theSYSDATETIME()
value as a constant, and completely ignoring any operations likeDATEADD()
that are performed against it.Paul shared that the workaround is simply to use a
datetime
equivalent when calculating the date, before converting it to the proper data type. In this case, we can swap outSYSUTCDATETIME()
and change it toGETUTCDATE()
I suppose switching to GETUTCDATE isn’t too much of a loss, but it looks like (according to Paul White in the second linked Connect item) this appears to have been fixed in SQL Server 2014.
Comments closed