Friday, February 10, 2006

How To Check For A Certain Time With SQL

Sometimes you have jobs and you don't know how long they will run
Let's just assume here that the job has 2 steps
You run step 1 and it takes x hours, you only want to run step 2 if it's before 5:45 AM because some other job will start at 6:00 AM and you don't want those 2 jobs hitting the same table at the same time (a real world scenario might be different of course, this is just a simplified version)

I hardcoded 05:45:00.000 here, you can of course store this in a parameter or even in a table so that you only have to change it in one place


--Get today's date
DECLARE @CurrentDateTime DATETIME
SET @CurrentDateTime = GETDATE()

-- create a 2nd parameter and append the time that you need to check for
DECLARE @TimeToChek DATETIME
SELECT @TimeToChek = CONVERT(VARCHAR,@CurrentDateTime,101) + ' 05:45:00.000'



IF (@CurrentDateTime <= @TimeToChek)
-- It is before 5:45 AM
BEGIN
SELECT 'before 5:45am' OutputStatus,
@CurrentDateTime AS CurrentTime,
@TimeToChek AS TimeToCheck
END
ELSE
-- it is before 5:45 AM
BEGIN
SELECT 'Not before 5:45am' OutputStatus,
@CurrentDateTime AS CurrentTime,
@TimeToChek AS TimeToCheck
END

No comments: