Accuracy of SYSDATETIME Data Type in SQL Server

不羁的心 提交于 2019-12-11 00:09:48

问题


I have done some testing using the SYSDATETIME in stored procedure in SQL Server 2008. I have setup a table with a datetime2(7) with a IDENTITY field.

I understand the difference between the precision and the accuracy of this data type however, I noticed an unusual result when inserting multiple records from this example:

declare @counter int
    set @counter = 0
    while @counter < 100000
    begin
      set @counter = @counter + 1
        INSERT INTO t ([now]) VALUES (SYSDATETIME())
    end

I looped through using an insert statement 100,000 to determine if the SYSDATETIME is working correctly as I expect it to. However, it appears that it is not much more accurate compared to GETDATE.

2015-12-01 19:16:58.4102452
2015-12-01 19:16:58.4102452
2015-12-01 19:16:58.4112452
2015-12-01 19:16:58.4112452
2015-12-01 19:16:58.4122453
2015-12-01 19:16:58.4122453
2015-12-01 19:16:58.4132453
2015-12-01 19:16:58.4152455
2015-12-01 19:16:58.4152455
2015-12-01 19:16:58.4162455
2015-12-01 19:16:58.4162455
2015-12-01 19:16:58.4172456
2015-12-01 19:16:58.4172456
2015-12-01 19:16:58.4182456
2015-12-01 19:16:58.4182456
2015-12-01 19:16:58.4192457
2015-12-01 19:16:58.4192457
2015-12-01 19:16:58.4202457
2015-12-01 19:16:58.4202457
2015-12-01 19:16:58.4212458

From my observation, the last four decimals places appear to be incrementing independent of the first three digits. This is the trend for the 100,000 inserts that were performed.

If you notice the last two decimal second times in this small sample extract, it jumps from .4212457 to .4212458.

Whilst it has the precision of the 7 places, the accuracy in my view is only 3 places. The last four digits is running in an incremental fashion independent of the time. I would expect that the last 4 decimal places in the time value would be completely random upon each insert into the database.

Is this a correct statement, or is there a right method to obtain truly accurate/random time?


回答1:


It depends on your system. The following is taken from MS Docs:

SQL Server obtains the date and time values by using the GetSystemTimeAsFileTime() Windows API. The accuracy depends on the computer hardware and version of Windows on which the instance of SQL Server is running. The precision of this API is fixed at 100 nanoseconds. The accuracy can be determined by using the GetSystemTimeAdjustment() Windows API.

I hope this helps.

Edit

Replaced MSDN link with MS Docs.



来源:https://stackoverflow.com/questions/34016556/accuracy-of-sysdatetime-data-type-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!