Simple DateTime sql query

ove picture ove · May 25, 2011 · Viewed 499.7k times · Source

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'."

Answer

Alex Aza picture Alex Aza · May 25, 2011

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'