开发者

composing a SQL query with a date offset

I am trying to do this:

select * from table 
where ChangingDate(this is 开发者_运维问答a column which has date and time) = today's date + 1

I am a learner of SQL, and I am bad at date formats. I appreciate if someone can help.

Thank you!


This will return tomorrow's data

WHERE ChangingDate > = dateadd(dd, datediff(dd, 0, getdate())+1, 0)
and ChangingDate < dateadd(dd, datediff(dd, 0, getdate())+2, 0)

This will return today's data

WHERE ChangingDate > = dateadd(dd, datediff(dd, 0, getdate())+0, 0)
and ChangingDate < dateadd(dd, datediff(dd, 0, getdate())+1, 0)

See also How Does Between Work With Dates In SQL Server?


There's a trick with datetimes in databases - you almost never want an = comparison, because as you saw they also include a time component. Instead, you want to know if it falls inside a range that includes the entire day. Sql Server 2008 has a new date type that helps with this, but until you upgrade, do it like this:

WHERE (ChangingDate >= dateadd(dd,1, datediff(dd,0, getDate())) 
       AND ChangingDate < dateadd(dd,2, datediff(dd,0, getDate())))

You can do an equals comparison if you are certain that all the records have a 0-value (or other known value) for the time component in that column. What you don't want to do is truncate the column, because that means doing extra work per-record (slow) and will break your index (very slow).


select *
  from MyTable
 where DATEADD(dd, 0, DATEDIFF(dd, 0, ChangingDate)) = SELECT DATEADD(dd, 1, DATEDIFF(dd, 0, GETDATE()))


you may want to try something like

select * from table where columndate=GetDate() + 1


Sounds like you want the DATEPART function to find where the column date has the same year, month, day regardless of time of day:

SELECT * FROM Table 
WHERE 
    DATEPART(Month, Date) = DATEPART(Month, @SomeDate) 
AND DATEPART(Day, Date) = DATEPART(Day, @SomeDate) 
AND DATEPART(Year, Date) = DATEPART(Year, @SomeDate)

Otherwise, you want to use DateAdd like the other posters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜