Using SQL Server 2008.
Let’s say I have 3 numbers to store.
- First number is any 6bit number
- Second is any 4bit
- Third is also any 6bit number
For example:
declare @firstNumber_6bit tinyint = 50
declare @secondNumber_4bit tinyint = 7
declare @thirdNumber_6bit tinyint = 63
I need to store those 3 numbers in a 2 byte binary (16bit) variable. So, the binary values for the example are:
- 50 is
110010, - 7 is
0111 - 63 is
111111 - The 2 bytes to store are
1100100111111111
So either one of the following lines should store those values:
declare @my3NumbersIn2Bytes binary(2) = 51711
or
declare @my3NumbersIn2Bytes binary(2) = 0xC9FF
(sorry if I’m messing the byte order in big / little endian, but that’s not the point).
Storing and retriving those numbers is a trivial task with .net CLR, but I’m trying to solve this in pure T-SQL and as we know there is no bit shifting in SQL Server. I saw a lot of examples out there that use memory tables to solve problems like these, but that seems totally overkill for doing a simple bit shift… I was thinking something more like a substring for bits could do the trick. I just want to be sure there’s no other way to solve this before going the overkill way.
So my question is, what is the most effective way to store those 3 numbers and recover them?
Thanks.-
SQL Fiddle Demo