Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 simple query question

Author  Topic 

bill_
Starting Member

38 Posts

Posted - 2009-04-24 : 11:45:58
HOw do you query for rows where 2 date columns are within 1 day of each other?

One date is a datetime and the other is a string like '20081225'.

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2009-04-24 : 13:13:13
Here is one way:
--Set up sample data
DECLARE @Table TABLE (ID INT PRIMARY KEY, Date1 DATETIME, Date2 VARCHAR(8))

INSERT @Table
SELECT 1, '2009-04-24 10:10:00' , '20090422'
UNION ALL SELECT 2, '2009-04-24 10:10:00' , '20090423'
UNION ALL SELECT 3, '2009-04-24 10:10:00' , '20090424'
UNION ALL SELECT 4, '2009-04-24 10:10:00' , '20090425'
UNION ALL SELECT 5, '2009-04-24 10:10:00' , '20090426'

-- Run Query
SELECT *
FROM @Table
WHERE ABS(DATEDIFF(DAY, Date1, CAST(Date2 AS DATETIME))) = 1
Go to Top of Page
   

- Advertisement -