Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search between dates and times in SQL Server 2008

I need to search between dates and times.

For example, between date: 30/02/2007, time: 10:32 and date: 21/06/2008, time: 14:19

What is the most simple query for this?

Thanks in advance.

like image 696
Gold Avatar asked Mar 17 '10 13:03

Gold


People also ask

How can I get data between two timestamps in SQL?

As stated above, the format of date and time in our table shall be yyyy:mm: dd hh:mm: ss which is implied by DATETIME2. The time is in a 24-hour format. Syntax: SELECT * FROM TABLE_NAME WHERE DATE_TIME_COLUMN BETWEEN 'STARTING_DATE_TIME' AND 'ENDING_DATE_TIME';

How can I get data between two dates in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference.

How do I pass a date range in SQL query?

SELECT * FROM PERSONAL WHERE BIRTH_DATE_TIME BETWEEN '2000-01-01 00:00:00' AND '2002-09-18 12:00:00';


1 Answers

you should look at the date time formats available in SQL Server: http://msdn.microsoft.com/en-us/library/ms187928.aspx

yyyy-mm-dd hh:mi is what you should use:

try:

SELECT
    *
    FROM Records
    WHERE DateCreated>='2007-02-30 10:32' AND DateCreated<='2008-06-21 14:19'

in the above query the strings will be converted to datetime data type if DateCreated is a datetime column. and the query will work.

you can create local variables of datetime data type and use a query like:

DECLARE @StartDate datetime, @EndDate datetime

SELECT @StartDate='2007-02-30 10:32', @EndDate='2008-06-21 14:19'

SELECT
    *
    FROM Records
    WHERE DateCreated>=@StartDate AND DateCreated<=@EndDate

I like using <, <=, >=, or > because it allows more flexibility than BETWEEN and forces you to think about including endpoints or not.

Another thing to consider is getting all data from a complete day:

DECLARE @StartDate datetime, @EndDate datetime

--set the days you want
SELECT @StartDate='2007-02-30 10:32', @EndDate='2008-06-21 14:19'

--remove the time
SELECT @StartDate=DATEADD(day,DATEDIFF(day,0,@StartDate),0), @EndDate=DATEADD(day,DATEDIFF(day,0,@EndDate),0)

--get everything on '2007-02-30' up to the end of the day on '2008-06-21'
SELECT
    *
    FROM Records
    WHERE DateCreated>=@StartDate AND DateCreated<@EndDate+1
like image 76
KM. Avatar answered Dec 30 '22 04:12

KM.