Compare DATETIME and DATE ignoring time portion

前端 未结 5 2419
清酒与你
清酒与你 2020-11-27 03:13

I have two tables where column [date] is type of DATETIME2(0).

I have to compare two records only by theirs Date parts (day+month+year), di

5条回答
  •  攒了一身酷
    2020-11-27 03:35

    Though I upvoted the answer marked as correct. I wanted to touch on a few things for anyone stumbling upon this.

    In general, if you're filtering specifically on Date values alone. Microsoft recommends using the language neutral format of ymd or y-m-d.

    Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.

    To do a date comparison using the aforementioned approach is simple. Consider the following, contrived example.

    --112 is ISO format 'YYYYMMDD'
    declare @filterDate char(8) = CONVERT(char(8), GETDATE(), 112)
    
    select 
        * 
    from 
        Sales.Orders
    where
        CONVERT(char(8), OrderDate, 112) = @filterDate
    

    In a perfect world, performing any manipulation to the filtered column should be avoided because this can prevent SQL Server from using indexes efficiently. That said, if the data you're storing is only ever concerned with the date and not time, consider storing as DATETIME with midnight as the time. Because:

    When SQL Server converts the literal to the filtered column’s type, it assumes midnight when a time part isn’t indicated. If you want such a filter to return all rows from the specified date, you need to ensure that you store all values with midnight as the time.

    Thus, assuming you are only concerned with date, and store your data as such. The above query can be simplified to:

    --112 is ISO format 'YYYYMMDD'
    declare @filterDate char(8) = CONVERT(char(8), GETDATE(), 112)
    
    select 
        * 
    from 
        Sales.Orders
    where
        OrderDate = @filterDate
    

提交回复
热议问题