Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple DateTime sql query

How do I query DateTime database field within a certain range?

I am using SQL SERVER 2005

Error code below

SELECT *    FROM TABLENAME   WHERE DateTime >= 12/04/2011 12:00:00 AM     AND DateTime <= 25/05/2011 3:53:04 AM 

Note that I need to get rows within a certain time range. Example, 10 mins time range.

Currently SQL return with Incorrect syntax near '12'."

like image 622
ove Avatar asked May 25 '11 03:05

ove


People also ask

How do I create a datetime table in SQL?

To declare a date variable, use the DECLARE keyword, then type the @variable_name and variable type: date, datetime, datetime2, time, smalldatetime, datetimeoffset. In the declarative part, you can set a default value for a variable. The most commonly used default value for a date variable is the function Getdate().

Is there a datetime in SQL?

What is the datetime data type? In SQL, datetime date data type is used for values that contain both date and time. Microsoft defines it as a date combined with a time of day with fractional seconds that is based on a 24-hour clock.


1 Answers

You missed single quote sign:

SELECT *  FROM TABLENAME  WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM' 

Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.

SELECT * FROM TABLENAME  WHERE      DateTime >= '2011-04-12T00:00:00.000' AND      DateTime <= '2011-05-25T03:53:04.000' 
like image 94
Alex Aza Avatar answered Oct 03 '22 10:10

Alex Aza