Using SQL Server 2008 R2, SP2
The docs says that datetime2 takes 6, 7 or 8 bytes depending witch precision you use
I need to store a large amount of data in binary form (concatenated values) and I love the idea of using only 6 bytes for each datetime, however when I try:
declare @_dt_p0 datetime2(0) = '2012-05-18 11:22:33'
select CONVERT(varbinary, @_dt_p0), LEN(CONVERT(varbinary, @_dt_p0))
declare @_dt_p4 datetime2(4) = '2012-05-18 11:22:33'
select CONVERT(varbinary, @_dt_p4), LEN(CONVERT(varbinary, @_dt_p4))
declare @_dt_p7 datetime2(7) = '2012-05-18 11:22:33'
select CONVERT(varbinary, @_dt_p7), LEN(CONVERT(varbinary, @_dt_p7))
It’s clearly taking one extra byte, what I’m doing wrong?
I don’t think I can explain why the length / datalength of a varbinary conversion is 7 instead of 6 (Mikael later found that the convert to varbinary adds the precision as an extra byte), but I don’t know why you think that’s a valid test anyway. I can confirm that 6 bytes are stored on the page when you are using an actual column (though null overhead for the row will be different depending on whether the column is nullable). How can I prove this?
Results:
So, the datetime2 columns are 6 bytes, but the varbinary columns are 7 bytes. Regardless of nullability. We can look closer by actually inspecting the page. Let’s find all the pages in the heap for this table:
Partial results on my system (yours will be different):
So now let’s look at Page 311:
And we can see that the datetime2 columns indeed occupy 6 bytes on the page: