Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to query where date with time = date without time in ms sql

Tags:

sql-server

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

like image 531
comfreakph Avatar asked Feb 13 '14 04:02

comfreakph


People also ask

How can I get only date from timestamp in SQL query?

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.

How can I get just date from DateTime?

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.

How can I get only date from DateTime datatype in SQL Server?

In SQL Server 2008 and above, we can either use the CONVERT or CAST function to return the DATE part from the DATETIME datatype.


2 Answers

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) ;
like image 69
Gordon Linoff Avatar answered Oct 02 '22 15:10

Gordon Linoff


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')

SQL FORMAT

like image 38
Vignesh Kumar A Avatar answered Oct 02 '22 15:10

Vignesh Kumar A