最近使用sqlserver 2012的时候注意到datetime类型的毫秒的精度是存在问题的,好奇是怎么回事,特意来研究一下
问题复现
如下的sql执行
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.000' Where id=1;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.001' Where id=2;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.002' Where id=3;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.003' Where id=4;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.004' Where id=5;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.005' Where id=6;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.006' Where id=7;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.007' Where id=8;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.008' Where id=9;
UPDATE AlarmItem SET create_time = '2024-01-01 00:00:00.009' Where id=10;
select id,create_time from AlarmItem where id in (1,2,3,4,5,6,7,8,9,10)
不点开下面的执行结果,想想看,觉得答案会是怎么样?
点击查看执行结果
1 2024-01-01 00:00:00.000
2 2024-01-01 00:00:00.000
3 2024-01-01 00:00:00.003
4 2024-01-01 00:00:00.003
5 2024-01-01 00:00:00.003
6 2024-01-01 00:00:00.007
7 2024-01-01 00:00:00.007
8 2024-01-01 00:00:00.007
9 2024-01-01 00:00:00.007
10 2024-01-01 00:00:00.010
可以注意到,数据并没有按照我们期望的那样,例如001 存入后变成了000 而002变成了003,这个原因是什么呢?
探究原因
翻看微软的官方文档可以发现在SQL Server中,DateTime的精度是3.33毫秒,也就是存在精度丢失的情况
同时微软自己定义了关于DateTime时间舍入的规则
总结一下就是:
9进0
0、1舍入为0
2、3、4舍入为3
5、6、7、8舍入为7