3

我必须在 mssql db 中存储一些间隔。我知道日期时间的准确性约为。3.3ms(只能结束0、3和7)。但是当我计算日期时间之间的间隔时,我发现结果只能以 0、3 和 6 结尾。所以我总结的间隔越多,我的精度就越松。是否有可能在毫秒内获得准确的 DATEDIFF?

declare @StartDate datetime
declare @EndDate datetime

set @StartDate='2010-04-01 12:00:00.000'
set @EndDate='2010-04-01 12:00:00.007'

SELECT DATEDIFF(millisecond, @StartDate, @EndDate),@EndDate-@StartDate, @StartDate, @EndDate

我希望看到 7 个广告而不是 6 个。(并且应该尽可能快)

** 更新 **

我可以看到 DATEDIFF 值不仅以 0、3、6 结尾,而且还以 4、7 结尾(可能还有其他值),但问题是它们仍然不准确。亚历克斯建议的解决方案正在奏效。如果您不想记住正确的日期时间格式,也可以使用:

SELECT DATEDIFF(SECOND, @StartDate, @EndDate)*1000 + DATEPART(MILLISECOND , @EndDate) - DATEPART(MILLISECOND , @StartDate)

我仍然想知道为什么DATEDIFF(millisecond, @StartDate, @EndDate)不准确?

4

5 回答 5

2

如何计算 MS 差异(减去DATEPARTs 时准确)然后将其添加到DATEDIFF不包括 MS 的差异中?

SELECT DATEDIFF(MILLISECOND, CONVERT(VARCHAR, @StartDate, 120), CONVERT(VARCHAR, @EndDate, 120)) + DATEPART(MILLISECOND , @endDate) - DATEPART(MILLISECOND , @StartDate)

为 .003->.007 提供 4,为 .000->.007 提供 7

于 2010-04-27T09:56:05.053 回答
0

或者您可能希望使用更准确的 DATETIME2 日期类型:

declare @StartDate datetime2
declare @EndDate datetime2

set @StartDate='2010-04-01 12:00:00.000'
set @EndDate='2010-04-01 12:00:00.007'

SELECT DATEDIFF(millisecond, @StartDate, @EndDate)

选择 7 作为结果。

查看SQL Server 中的 DateTime2 与 DateTime

于 2014-05-13T09:57:49.823 回答
0

怎么用DatePart

declare @StartDate datetime
declare @EndDate datetime

set @StartDate='2010-04-01 12:00:00.000'
set @EndDate='2010-04-01 12:00:00.007'

SELECT DATEDIFF(millisecond, @StartDate, @EndDate),
        DatePart(millisecond, @EndDate-@StartDate),
        @StartDate, @EndDate
于 2010-04-27T08:16:25.107 回答
0

像这样试试

   SELECT DATEDIFF(millisecond, @StartDate, dateadd(day,1,@EndDate)),dateadd(day,1,@EndDate)-@StartDate, @StartDate, @EndDate
于 2010-04-27T08:20:19.113 回答
0

I think the issue here is that your accuracy requirements are too much for the datetime datatype.

If rounding to 6 or 7 milliseconds is an issue then you will never get the accuracy you need.

Are the intervals you have continuous? If so, could you just store a single date and then calculate the milliseconds between the first start date and the last end date?

Alternatively, can you obtain the interval using your client language? Then store the intervals as an int/long? You could possibly store the start date and the interval in milliseconds calculated in code rather than storing a start and end date in sql.

于 2010-04-27T08:26:09.477 回答