I want to do a query with dates this is my sample tsql:
select * from Bookings where StartTime = '2/15/2014'
the starttime has value '2/15/2014 12:00:00 AM'
when I query where StartTime = date with no time the result is 0
Anybody can help how to do this?
thanks
In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column.
ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.
In SQL Server 2008 and above, we can either use the CONVERT or CAST function to return the DATE part from the DATETIME datatype.
The best way to do this is with a simple comparison:
select *
from Bookings
where StartTime >= cast('2014-02-15' as date) and StartTime < cast('2014-02-14' as date);
This is the safest method of comparison, because it will take advantage of an index on StartTime
. This property is called "sargability".
In SQL Server, casting to a date
should also be sargable, so you could also do:
select *
from Bookings
where cast(StartTime as date) = cast('2014-02-15' as date) ;
Try like this
SELECT * FROM Bookings WHERE Convert(VARCHAR(10),StartTime,101) = Convert(Varchar(10),'2/15/2014',101)
If you are using SQL SERVER 2012
Try this
SELECT * FROM Bookings WHERE FORMAT(StartTime,'M/dd/yyyy') = FORMAT('2/15/2014','M/dd/yyyy')
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