2

I have a SQL SERVER Table which has only one field "StartDate" the records are as follows

** 2011-07-28 19:30:00.000

2011-07-29 21:50:00.000

2011-07-25 09:20:00.000 **

What i want to do is :

SHOW RECORDS if its CURRENT DATE ( todays date ) and the time difference between current time the StartDate is not less then 5 minutes, i have written the following code but it doesnt show me the time difference ?

SELECT * FROM table WHERE DATEDIFF(day, StartDate, GETDATE()) <= 0

4 Answers 4

3
SELECT StartDate
FROM table
WHERE YEAR(StartDate)=YEAR(GETDATE())
AND MONTH(StartDate)=MONTH(GETDATE())
AND DAY(StartDate)=DAY(GETDATE())
AND (DATEDIFF(minute, StartDate, GETDATE()) >= 5
     OR
     DATEDIFF(minute, StartDate, GETDATE()) <= 5) 
Sign up to request clarification or add additional context in comments.

Comments

0

How about:

SELECT StartDate
    ,GETDATE()
    ,DATEDIFF(day, StartDate, GETDATE())
    ,DATEDIFF(minute, StartDate, GETDATE())
    ,*
FROM table
WHERE DATEDIFF(day, StartDate, GETDATE()) <= 0
    AND DATEDIFF(minute, StartDate, GETDATE()) >= 5

2 Comments

DATEDIFF(day, StartDate, GETDATE()) - wouldn't this return minus values for past days? Doesnt the user only want records for todays date?
@Curt, it would return a negative for future starts. The first DATEDIFF ensures it is the same day (or future, I'm not sure why he put that in there). I considered putting an ABS in there, but the poster wasn't clear about what he was looking for.
0

There are two ways to do it one being DateDiff the other is DATEADD. Judging by the way I read your question DateAdd should do it. Here is an example;

    SELECT *
  FROM [dbo].[TABLE]
  WHERE [LAST_UPDATE] > DATEADD(minute,-5,GetDate())

Comments

0

Using BETWEEN is probably a little more optimal than two AND statements (maybe not). Try not to do a calculation on each row if you don't have to. Doing DATEADD only on the current date will only be calculated once.

SELECT 
   whatever
FROM
   table
WHERE 
    StartDate
        BETWEEN FLOOR( CAST( GETDATE() AS FLOAT ) )
        AND DATEADD(minute, -5, GETDATE())

I interpret the question as looking for rows where the date is today (between the start of today) but not within the last 5 minutes (and less than 5 minutes ago). That might not be what you were going for.

Hope that helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.