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?
The SYSDATETIME() function returns the date and time of the computer where the SQL Server is running.
The main difference between GETDATE() and SYSDATETIME() is that GETDATE returns the current date and time as DATETIME but SYSDATETIME returns a DATETIME2 value, which is more precise.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With