kick it on DotNetKicks.com   Shout it  

SARGable DateTime Handling in SQL Server

I can't believe I never thought of doing things this way before. It's so much better than concatenating strings and converting back and forth between varchar, int and datetime. I'd like to thank Marc for posting this jewel. Here's the link to the original content: Marc's Musings: More on DATEs and SQL.

I'm including the actual functions below, just as a quick reference:

SELECT DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0) As Today,
DATEADD(wk, DATEDIFF(wk, 0, GetDate()), 0) As ThisWeekStart,
DATEADD(mm, DATEDIFF(mm, 0, GetDate()), 0) As ThisMonthStart,
DATEADD(qq, DATEDIFF(qq, 0, GetDate()), 0) As ThisQuarterStart,
DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) As ThisYearStart,
DATEADD(dd, DATEDIFF(dd, 0, GetDate()) + 1, 0) As Tomorrow,
DATEADD(wk, DATEDIFF(wk, 0, GetDate()) + 1, 0) As NextWeekStart,
DATEADD(mm, DATEDIFF(mm, 0, GetDate()) + 1, 0) As NextMonthStart,
DATEADD(qq, DATEDIFF(qq, 0, GetDate()) + 1, 0) As NextQuarterStart,
DATEADD(yy, DATEDIFF(yy, 0, GetDate()) + 1, 0) As NextYearStart,
DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()) + 1, 0)) As TodayEnd,
DATEADD(ms, -3, DATEADD(wk, DATEDIFF(wk, 0, GetDate()) + 1, 0)) As ThisWeekEnd,
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetDate()) + 1, 0)) As ThisMonthEnd,
DATEADD(ms, -3, DATEADD(qq, DATEDIFF(qq, 0, GetDate()) + 1, 0)) As ThisQuarterEnd,
DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, GetDate()) + 1, 0)) As ThisYearEnd

Tags: ,

kick it on DotNetKicks.com   Shout it  

Feedback

# 

Gravatar Thanks, this helped a lot! 3/21/2008 8:55 AM | noreply@blogger.com (Anonymous)

# 

Gravatar Glad you liked it :) 4/13/2008 2:16 PM | noreply@blogger.com (IDisposable)

# 

Gravatar Hey Mark,
I just went through www.codeproject.com/.../dbloadbalancerservice.aspx and now this blog. Great work and I'll be checking back in for more. Since my skills are just developing in this area, this has been very helpful in moving forward in the design of the enviroment for my app.

Again, great work on both sites.

Thanks,
Eldon 4/17/2008 1:08 PM | noreply@blogger.com (Anonymous)

Post a comment





 

Please add 5 and 2 and type the answer here:

 

 

Copyright © Mark J. Miller