CAST(DATETIME AS DATE) over WHERE clause

后端 未结 3 590
心在旅途
心在旅途 2021-01-06 12:31

I\'m using SQL Server 2012 and I would like to know if I write the sentence:

SELECT MyDateTimeColumn 
FROM MyTable
WHERE CAST(MyDateTimeColumn AS DATE) = \'         


        
3条回答
  •  花落未央
    2021-01-06 13:22

    Use this proven method to "zero out" the time component of a datetime:

    select MyDateTimeColumn
    from MyTable
    where DATEADD(dd, DATEDIFF(dd, 0, MyDateTimeColumn), 0) = CONVERT(date, '07-09-2014', 110)
    

    Avoid casting to different date types if there's a faster way (like the trick above), and definitely try to avoid using string literals for dates without wrapping them in a CONVERT() to ensure your string format will get interpreted correctly.

    If you have performance concerns and want to force it to use an index, I would suggest adding a column that is of type date (fill it with the existing column's value minus the time part), and index/search on that, or create an indexed view that accomplishes the same thing.

提交回复
热议问题