views:

23

answers:

5

Hello everyone,

I am using SQL Server 2008 Enterprise. I have a table called Foo and it has a DateTime type column called MyTime. I want to find all records (rows) whose MyTime column value has been elapsed for more than 3 days (elapsed from current time). How to implement this?

thanks in advance, George

+1  A: 

datediff(d,GetDate(),MyTime) > 3

select * from table
  where datediff(d,GetDate(),MyTime) > 3

Edit: It was the other way around :P

Christian W
This will give you the right answer, but it won't use indexes properly.
Bennor McCarthy
+1  A: 

You can use DATEADD(datepart, number, date) to do the calculation:

SELECT * FROM Foo WHERE MyTime > DATEADD(dd, -3, MyTime)
halfdan
+3  A: 
WHERE myTime < DATEADD(dd,-3,getDate())
HCL
Thanks, question answered!
George2
+3  A: 

If you have a lot of rows you'd probably want to remove per-row-expressions, so first find out what date is it that you seek, and then just compare:

DECLARE @DateExpired DATETIME
SET @DateExpired = GETDATE() - 3
SELECT * 
FROM Foo
WHERE MyTime < @DateExpired
veljkoz
I don't think you need to break the `GETDATE() - 3` into another statement. It should only be executed once even if you put it in the body of the query, because the planner will be smart enough to realise it's a constant value. This is still the best answer though.
Bennor McCarthy
Yes, agreed... it's just a habbit to keep queries clean...
veljkoz
+1  A: 
create table #foo
(
MyTime dateTime
)

Insert Into #foo
Values ('2010-09-15')
Insert Into #foo
Values ('2010-09-14')
Insert Into #foo
Values ('2010-09-13') 
Insert Into #foo
Values ('2010-09-12')


Select * FRom #foo
Where DateAdd(day, 3, MyTime) <= '2010-09-16'

drop table #foo
Barry