Convert SQL server datetime fields to compare date parts only, with indexed lookups

前端 未结 5 766
野性不改
野性不改 2020-11-30 00:23

I\'ve been doing a convert(varchar,datefield,112) on each date field that I\'m using in \'between\' queries in SQL server to ensure that I\'m only accounting fo

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 00:46

    Converting numeric types to string values (a type of Boxing) is not the best performing method of doing what you are looking for. Its not really about index-able, because the actual column type is date time.

    If you are looking for the best way query for dates, then your example is right, but you may want to take into account the 3 ms precision difference in MSSQL. It can mean that records from one day can show up in another day's result.

    This

    select * from appointments where appointmentDate>='08-01-2008' and appointmentDate<'08-15-2008'
    

    Should be this

    select * from appointments where appointmentDate>='08-01-2008' and appointmentDate<='08-14-2008 23:59:59.996'
    

提交回复
热议问题