views:

90

answers:

4

Hello,

I have such a simple question, I feel stupid for asking it. I can't believe I'm hitting my head on this.

I have a table called "Orders". "Orders" has a smalldatetime field called "DateOrdered". I need to get all of the "Orders" on a specific date. I have tried the following without any success:

SELECT * FROM Orders WHERE [DateOrdered]=2010-06-01

SELECT * FROM Orders WHERE [DateOrdered]='2010-06-01'

SELECT * FROM Orders WHERE [DateOrdered]=CAST('2010-06-01' AS smalldatetime)

What am I doing wrong? I can't believe I'm even asking this question.

+3  A: 

The first query compares the date to the number 2003 (2010 minus 6 minus 1) which converts into the date '1905-06-27'. The second and third query would work for exact date values (i.e. with a 00:00 time component), and are equivalent.

Do you have a time component in your smalldatetime values? In that case you can get the values in an interval:

SELECT * FROM Orders WHERE DateOrdered >= '2010-06-01' 
                       and DateOrdered < '2010-06-02'

Notice the use of >= and < instead of the between keyword, to exclude any records that might have the exact value 2010-06-02.

Guffa
my solution might be more flexible rather than using +1 days but I guess it depends on how he's executing the SQL
hunter
+2  A: 

Like this, also notice the safe ISO date format (YYYYMMDD) which won't blow up if you are in the UK for example

SELECT * FROM Orders WHERE [DateOrdered] >='20100601'
AND [DateOrdered] < '20100602'

This way also will enable you to use an index, if you cast the DateOrdered column an index won't be used

here is an example of what happens when you use YYYY-MM-DD instead of YYYYMMDD

SET LANGUAGE 'us_english'

SELECT CONVERT(DATETIME, '2006-04-06'),  --will be YMD
       CONVERT(DATETIME, '20060406')  --safe format

SET LANGUAGE 'Italian'

SELECT CONVERT(DATETIME, '2006-04-06'),  --will be YDM
       CONVERT(DATETIME, '20060406')  -- safe format
SQLMenace
+1  A: 

I always use this post to remember how to round a DATETIME into a "DATE" for SQL2005 and earlier: http://stackoverflow.com/questions/1177449/best-approach-to-remove-time-part-of-datetime-in-sql-server

Bill
+1  A: 

I suggest that you use DATEDIFF

SELECT * FROM Orders WHERE DATEDIFF(d, [DateOrdered], '20100601') = 0
Vanilj