简体   繁体   中英

Comparison of datetime in sql server

I am storing datetime to database as a standard datetime like 2011-10-19 17:18:44.083. I need to select all the rows if the datetime field is equals to 5 days after today. But I dont want this comparison also in time just the day is enough.

SELECT * FROM dbo.TestBox
where TargetDate = dateadd(day,5, getdate()) 

This is not working, I dont know exactly why but probably its looking at time.

Thanks in advance,

If you're using 2008+, you can cast both as a Date:

where convert(date, targetdate) = convert(date, dateadd(day, 5, getdate()))

If you're using 2005 or prior, do something like this:

where convert(varchar, targetdate, 101) = convert(varchar, dateadd(day, 5, getdate()), 101)

You can do:

SELECT * FROM dbo.TestBox
where CONVERT(VARCHAR(8),TargetDate,112) = CONVERT(VARCHAR(8),dateadd(day,5, getdate()),112)

Or, if you have an index on TargetDate:

SELECT * FROM dbo.TestBox
where TargetDate >= CONVERT(VARCHAR(8),dateadd(day,5, getdate()),112) 
AND TargetDate < CONVERT(VARCHAR(8),dateadd(day,6, getdate()),112) 

Try:

select * 
from dbo.TestBox 
where datediff(dd, getdate(), TargetDate) = 5

Sample code:

declare @targetDate as DateTime
set @targetDate = '2011-11-2'
select datediff(dd, getdate(), @targetDate)

Output:

5

DATEDIFF to the rescue!

DECLARE @monday DATETIME;
DECLARE @fridayAM DATETIME;
DECLARE @fridayPM DATETIME;
SET @monday = '2011-10-23 10:50:00';
SET @fridayAM = '2011-10-28 08:00:00';
SET @fridayPM = '2011-10-28 17:30:00';
SELECT DATEDIFF(DAY, @monday, @fridayAm) AS AmDiff, 
       DATEDIFF(DAY, @monday, @fridayPm) AS PmDiff

Both AmDiff and PmDiff will be 5.

The following query should do what is required.

SELECT * FROM dbo.TestBox 
WHERE TargetDate 
        BETWEEN DATEADD(DAY, 5, DATEADD(MILLISECOND, 1, DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)))
        AND DATEADD(DAY, 5, DATEADD(MILLISECOND, -2, DATEADD(DAY, datediff(day, 0, GETDATE()) + 1, 0))) -- between the start and end of the date in 5 days

The issue could be due to different date formats.

This link has all the date formatting options in sql http://databases.aspfaq.com/database/what-are-the-valid-styles-for-converting-datetime-to-string.html

Try something like :

SELECT * FROM dbo.TestBox where CONVERT(CHAR(8), TargetDate , 1)= dateadd(day,5, (CHAR(8), getdate(), 1))  

This converts both dates you are comparing to the same format and looses the time part

Instead of using GETDATE() you could also use CURRENT_TIMESTAMP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM