What's a good way to check if two datetimes are on the same calendar day in TSQL?

前端 未结 10 1417
小鲜肉
小鲜肉 2021-02-12 02:15

Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which suck

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-12 03:11

    Eric Z Beard:

    the activity date is meant to indicate the local time zone, but not a specific one

    Okay - back to the drawing board. Try this:

    where t.TheDateINeedToCheck BETWEEN (
        dateadd(hh, (tz.Offset + ISNULL(ds.LocalTimeZone, 0)) * -1, @ActivityDate)
        AND
        dateadd(hh, (tz.Offset + ISNULL(ds.LocalTimeZone, 0)) * -1, (@ActivityDate + 1))
    )
    

    which will translate the @ActivityDate to local time, and compare against that. That's your best chance for using an index, though I'm not sure it'll work - you should try it and check the query plan.

    The next option would be an indexed view, with an indexed, computed TimeINeedToCheck in local time. Then you just go back to:

    where v.TheLocalDateINeedToCheck BETWEEN @ActivityDate AND (@ActivityDate + 1)
    

    which would definitely use the index - though you have a slight overhead on INSERT and UPDATE then.

提交回复
热议问题