I'm trying to optimize several queries that all use a similar pattern on one of the WHERE
clauses:
AND (DATEADD(DAY
, ISNULL(a.[due_days], 30) + 30
, [dbo].[CalcDate]([type], date1, date2, date3, date4, NULL))
) < GETDATE()
The CalcDate
udf based on the type
field value makes some comparisons and returns a date. Then adds an amount of days to that date and compares to current date. In order to be able to use an existing index on due_days
I want to transform the operation to apply all the transformations to GETDATE()
, let's say I want to make it sargable
, if possible. Also, if there is some recommendation on what can be done to improve the use of the udf even better.
Best Answer
It's not so hard to do this transformation. Step by step:
means:
then we have to break the
ISNULL()
into 2 cases:which can be written as:
so we can use
DATEDIFF()
:and finally:
Corrected, taking care of the time parts:
You could simplify it a bit, with the use of
CROSS APPLY
: