You can just use DateDiff
Returns the counter (signed integer) of the specified datepart boundaries that intersect between the specified start and end values.
select DATEDIFF(MILLISECOND, cast('20010101 23:45:21.12347' as datetime2), cast('20010105 12:35:15.56786' as datetime2))
Unfortunately, trying to get the accuracy you need:
select DATEDIFF(MICROSECOND, cast('20010101 23:45:21.12347' as datetime2), cast('20010105 12:35:15.56786' as datetime2))
results in an overflow error:
The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.
One way to achieve the required accuracy would be an iterative gap in the drilldown components (days, hours, minutes, seconds, etc.) and subtract this from the values ββusing DateAdd (), for example.
remainingAtLowerGranularity = DateAdd(granularity, -1 * numFoundInStep, value)
Mitch wheat
source share