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

后端 未结 17 1995
隐瞒了意图╮
隐瞒了意图╮ 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: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.

提交回复
热议问题