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

前端 未结 4 2035
臣服心动
臣服心动 2021-02-06 02:33

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/2

相关标签:
4条回答
  • 2021-02-06 02:35

    '2/15/2014' can be interpreted different depending on your locale. Try using the ISO date literal '2014-02-15', which is independent of the locale.

    select * from Bookings where StartTime = '2014-02-15'
    

    Or if StartTime includes hours:

    select * from Bookings where StartTime >= '2014-02-15' and StartTime < '2014-02'16'
    
    0 讨论(0)
  • 2021-02-06 02:43

    I believe you could also do this:

    select * from Bookings where StartTime::date = '2014-2-15'
    
    0 讨论(0)
  • 2021-02-06 02:48

    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

    0 讨论(0)
  • 2021-02-06 02:52

    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) ;
    
    0 讨论(0)
提交回复
热议问题