I've a table to keep list of tasks and these tasks need to be processed on specific date and time. Tricky part is these tasks are recursive running time must be calculated based on 5 different parameters.
Calculating running time through UDF was simple part:
Function dbo.task_next_run(
@task_type varchar(10),
@task_schedule_day_of_week varchar(20),
@task_schedule_time varchar(20),
@task_period smallint,
@last_run datetime
)
Returns datetime
...
...
...
Return @next_run
My final task query was this:
SELECT id,
task_name,
last_run
From tasks
Where dbo.task_next_run
(
task_type, @task_schedule_day_of_week,
@task_schedule_time, @task_period, @last_run
) < getdate() and
dbo.task_next_run
(
task_type, @task_schedule_day_of_week,
@task_schedule_time, @task_period, @last_run
) > last_run
My problem is running same function 2 times in where clause. I need a solution to use calculated value as alias in where clause.
GetDate()within a query is chasing a moving target, impacts performance, and may produce curious results, e.g. as the date changes. It is almost always a better idea to capture the current date/time in a variable and then use that value as needed. This is more important across multiple statements as in a stored procedure. The most common reason to useGetDate()multiple times is when capturing the start and end times for a long running operation.