How to query DATETIME field using only date in Microsoft SQL Server?

后端 未结 17 1889
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 06:31

I have a table TEST with a DATETIME field, like this:

ID NAME DATE
1 TESTING 2014-03-19 20:05:20.000


        
相关标签:
17条回答
  • 2020-12-02 06:54

    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:

    1. If you have control over the database schema, and you don't need the time data, take it out.

    2. 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'
    
    0 讨论(0)
  • 2020-12-02 06:55

    I am using MySQL 5.6 and there is a DATE function to extract only the date part from date time. So the simple solution to the question is -

     select * from test where DATE(date) = '2014-03-19';
    

    http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html

    0 讨论(0)
  • 2020-12-02 06:55

    you can try this

    select * from test where DATEADD(dd, 0, DATEDIFF(dd, 0, date)) = '03/19/2014';
    
    0 讨论(0)
  • 2020-12-02 06:56

    Simple answer;

    select * from test where cast ([date] as date) = '03/19/2014';
    
    0 讨论(0)
  • 2020-12-02 06:56
    select * from test 
    where date between '03/19/2014' and '03/19/2014 23:59:59'
    

    This is a realy bad answer. For two reasons.

    1. What happens with times like 23.59.59.700 etc. There are times larger than 23:59:59 and the next day.

    2. The behaviour depends on the datatype. The query behaves differently for datetime/date/datetime2 types.

    Testing with 23:59:59.999 makes it even worse because depending on the datetype you get different roundings.

    select convert (varchar(40),convert(date      , '2014-03-19 23:59:59.999'))
    select convert (varchar(40),convert(datetime  , '2014-03-19 23:59:59.999'))
    select convert (varchar(40),convert(datetime2 , '2014-03-19 23:59:59.999'))
    

    -- For date the value is 'chopped'. -- For datetime the value is rounded up to the next date. (Nearest value). -- For datetime2 the value is precise.

    0 讨论(0)
  • 2020-12-02 06:57

    Try this

     select * from test where Convert(varchar, date,111)= '03/19/2014'
    
    0 讨论(0)
提交回复
热议问题