views:

102

answers:

1

I understand there are multiple questions about this on SO, but I have yet to find a definitive answer of "yes, here's how..."

So here it is again: What are the possible ways to store an unsigned integer value (32-bit value or 32-bit bitmap) into a 4-byte field in SQL Server?

Here are ideas I have seen:

1) Use a -1*2^31 offset for all values

  • Disadvantages: need to perform math on the values before reading/writing/aggregating.

2) Use 4 tinyint fields

  • Disadvantages: need to concatenate values to perform any operations

3) Use binary(4)

  • Disadvantages: actually uses 4 + 2 bytes of space (Edit: varbinary(4) uses 4+2, binary(4) only uses 4)
  • Need to work in SqlBinary or cast to/from other types
+1  A: 

IMO, you have the correct answers to storing 2^32 positive values in 4 bytes: either a standard int and you do the math or a binary(4) which, contrary to what you have said, will only consume 4 bytes of space. (Only varbinary will incur an extra 2 bytes of storage). A series of tinyint or smallint columns would be unjustifiably cumbersome IMO.

Of course there is another solution for storing 2^32 positive values but it takes eight bytes: a bigint with a check constraint. Given how cheap storage and memory is today, IMO, this is the simplest and cheapest solution given the programmatic hoops you will have to jump through with the other solutions, however clearly you have a reason for wanting to save the extra 4 bytes on each row.

Thomas
Thanks - binary(4) is easy enough to work with. Now I wish I had a Bitwise-OR aggregate function.
Jeff Meatball Yang