I have a table TEST with a DATETIME
field, like this:
ID NAME DATE 1 TESTING 2014-03-19 20:05:20.000
What I need a query returning this row and every row with date 03/19/2014, no matter what the time is. I tried using
select * from test where date = '03/19/2014';
But it returns no rows. The only way to make it work that I found is to also provide the time portion of the date:
select * from test where date = '03/19/2014 20:03:02.000';
If you want to get a day from a date in a table, use the SQL Server DAY() function. This function takes only one argument – the date. This can be a date or date and time data type. (In our example, the column VisitDate is of the date data type.)
Just use the DATE and TIME functions: SELECT blah FROM tbl WHERE DATE(some_datetime_field) = '2012-04-02'; That will select any rows such that the date part of some_datetime_field is 4 Apr 2012.
SQL Date Data Types DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS. YEAR - format YYYY or YY.
use range, or DateDiff function
select * from test where date between '03/19/2014' and '03/19/2014 23:59:59'
or
select * from test where datediff(day, date, '03/19/2014') = 0
Other options are:
If you have control over the database schema, and you don't need the time data, take it out.
or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...
Alter table Test Add DateOnly As DateAdd(day, datediff(day, 0, date), 0)
or, in more recent versions of SQL Server...
Alter table Test Add DateOnly As Cast(DateAdd(day, datediff(day, 0, date), 0) as Date)
then, you can write your query as simply:
select * from test where DateOnly = '03/19/2014'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With