April 18, 2010

Select dates within the Current Week using SQL Server




One of the most common date queries I have seen is to select the dates matching the current week. Here’s how to do it

SAMPLE DATA

DECLARE @TT TABLE (CheckOut DATETIME)
INSERT INTO @TT VALUES ('March 15, 2010 11:25pm')
INSERT INTO @TT VALUES ('April 11, 2010 9:55am')
INSERT INTO @TT VALUES ('April 07, 2010 11:24am')
INSERT INTO @TT VALUES ('April 05, 2010 11:22pm')
INSERT INTO @TT VALUES ('April 13, 2010 5:27am')
INSERT INTO @TT VALUES ('April 16, 2010 8:21pm')
INSERT INTO @TT VALUES ('April 12, 2010 11:55am')
INSERT INTO @TT VALUES ('April 02, 2010 10:16am')
INSERT INTO @TT VALUES ('April 06, 2010 11:35am')
INSERT INTO @TT VALUES ('April 18, 2010 9:49pm')
INSERT INTO @TT VALUES ('April 12, 2010 7:55pm')

QUERY

SELECT GETDATE() as CurrentDateTime

SELECT * FROM @TT
WHERE CheckOut >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) / 7 * 7, 0)
AND
CheckOut < DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()), 0)

OUTPUT

Current Week SQL Server

As you can see, the query selects the dates only matching the current week.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

1 Response to "Select dates within the Current Week using SQL Server"
  1. Anonymous said...
    April 7, 2011 at 8:25 AM

    Thanks a lot !

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions