深入SQL Server 日期和时间的内部存储
在SQL Server的内部存储中,日期和时间不是以字符串的形式存储的,而是使用整数来存储的。使用特定的格式来区分日期部分和时间部分的偏移量,并通过基准日期和基准时间来还原真实的数据。
一,DateTime的内部存储
SQL Server存储引擎把DateTime类型存储为2个int32类型,共8个字节,第一个int32 整数(前4个字节)存储的是日期相对于基准日期(1900-01-01)的偏移量。基准日期是1900-01-01,当前4 字节为0 时,表示的日期是1900 年1 月1 日。第二个int32整数(后4个字节)存储的是午夜(00:00:00.000)之后的时钟滴答数,每个滴答为1⁄300秒,精确度为3.33毫秒(0.00333秒,3.33ms),因此,DateTime能够表示的时间,可能会存在一个滴答的时间误差。
DateTime的内部存储格式,用十六进制表示是:DDDDTTTT
- DDDD:占用2个字节,表示对基准日期的偏移量
- TTTT:占用两个字节,表示对午夜之后的始终滴答数
举个例子,对于如下的日期和时间,把DateTime类型转换为大小为8个字节的16进制,每两个数字对应1个字节:
declare @dt datetime = '2015-05-07 10:05:23.187'select convert(varbinary(8), @dt) as date_time_binary --output 0x0000A49100A6463C
1,拆分出date和time
把时间的二进制格式中的字节拆分成两部分:前4个字节表示date,后4个字节表示time,得出的结果如下:
declare @dt datetime = '2015-05-07 10:05:23.187'select substring(convert(varbinary(8), @dt), 1, 4) as date_binary, cast(substring(convert(varbinary(8), @dt), 1, 4) as int) as date_int, substring(convert(varbinary(8), @dt), 5, 4) as time_binary, cast(substring(convert(varbinary(8), @dt), 5, 4) as int) as time_int;
2,通过偏移量还原日期和时间
通过基准时间和偏移量,把整数还原为原始的日期和时间:
declare @Time time='00:00:00.000'declare @Date date='1900-01-01'