Compare time part of DateTime data type in SQL Server 2005

前端 未结 6 1868
梦谈多话
梦谈多话 2021-01-02 07:41

How can I compare only the time portion of a DateTime data type in SQL Server 2005? For example, I want to get all records in which MyDateField is after a specific time. The

6条回答
  •  鱼传尺愫
    2021-01-02 07:50

    What I wanted to do is to extract the time portion of a DateTime data type, and compare it. I found a way to extract the date portion here in StackOverflow. If I have the date part alone, it is just subtract the date from the source DateTime:

    datePortion = DATEADD(day, DATEDIFF(day,0, sourceDate), 0)
    timePortion = DATEDIFF(millisecond, datePortion, sourceDate)

    so the macro to extract the time portion in SQL Server 2005 is:

    f(x) = DATEDIFF(millisecond, DATEADD(day, DATEDIFF(day,0, sourceDate), 0), sourceDate)

    Now the query to compare the time portion of a DateTime field, with 12:30:50.400 is:

    SELECT *
    FROM   Table1
    WHERE
            DATEDIFF(millisecond, DATEADD(day, DATEDIFF(day, 0, DateTimeField), 0), DateTimeField)
            >
            DATEDIFF(millisecond, DATEADD(day, DATEDIFF(day, 0, '1900-01-01T12:30:50.400'), 0), '1900-01-01T12:30:50.400')
    

    I have tested this query against other kinds of queries, including using subtraction operator ('-'), and CONVERT. The execution plan comparison indicates that this is the fastest method to do this. I also tested the real times of query execution... there is no noticeable fastest method.

提交回复
热议问题