Jared
Jared

Reputation: 2483

TSQL: Date BETWEEN Query - Ignoring Time

I am trying to do a query between 2 dates. I would like to do it without having to worry about the time. When a user enters the 2 dates they want to search on, there is no selection for time. This means that the dates that they enter default to 12:00 AM.

The dates in the table do have times though. I just would like to ignore the times all together so the search brings back any records form said date range.

Here is my SQL:

TheDate BETWEEN @EnteredBeginDate AND @EnteredEndDate

So when a user does a range search between 8/6/2009 AND 9/9/2009 I want to return the records:

8/6/2009 11:33:02 AM
8/6/2009 11:39:17 AM
9/9/2009 8:21:30 AM

What's happening now is I only get back:

8/6/2009 11:33:02 AM
8/6/2009 11:39:17 AM

Can someone please recommend the best way to do this in SQL? I know how to do it in C#.

Upvotes: 11

Views: 13759

Answers (5)

Farhan
Farhan

Reputation: 2575

If you are using SQL Server 2008, then do this:

TheDate BETWEEN cast(@EnteredBeginDate as date) AND cast(@EnteredEndDate as date)

Upvotes: 2

JNK
JNK

Reputation: 65187

Just use DATEADD for the enddate to set it to midnight on the NEXT day...

TheDate BETWEEN @EnteredBeginDate AND DATEADD(day, 1, @EnteredEndDate)

If you want to be really precise, you could subtract a second or millisecond from that to make it 11:59:59 on your specified date:

TheDate BETWEEN @EnteredBeginDate AND DATEADD(second, -1, (DATEADD(day, 1, @EnteredEndDate)))

Upvotes: 10

Jon Raynor
Jon Raynor

Reputation: 3892

If just the date is passed into SQL Server, it will make the time 12:00 AM. So, the end date on the the between clause is 9/9/2009 12:00 AM. Just add a day or modify the date passed into the query to include the correct time.

Upvotes: 0

marc_s
marc_s

Reputation: 755013

If you're on SQL Server 2008 or 2008 R2, you could use the new DATE datatype:

TheDate BETWEEN CAST(@EnteredBeginDate AS DATE) AND CAST(@EnteredEndDate AS DATE)

That strips off the time portion and looks only at the date

Upvotes: 8

Brian Hoover
Brian Hoover

Reputation: 7991

TheDate BETWEEN @EnteredBeginDate AND dateadd(day, 1, @EnteredEndDate)

Upvotes: 1

Related Questions