sql server - How to concatenate bits to varbinary with CTE -
i have table ids , bits in following order:
id bit 1 0 1 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 1 0 1 ... ... ... 2 0 2 1 2 0 2 0 2 1 2 0 2 0 2 0 2 1 2 0 2 ... ... ... n ...
how group id column , concatenate bit column varbinary column using cte?
id bits 1 0x... 2 0x...
thanks in advance...
declare @bits table ( id int, position int, value int ); insert @bits ( id, position, value ) values ( 1, 0, 1 ), ( 1, 1, 1 ), ( 1, 2, 0 ), ( 1, 3, 1 ), ( 1, 4, 1 ), ( 1, 5, 1 ), ( 1, 6, 1 ), ( 1, 7, 0 ), ( 1, 8, 1 ), ( 1, 9, 0 ), ( 1, 10, 1 ), ( 1, 11, 0 ), ( 1, 12, 1 ), ( 1, 13, 1 ), ( 1, 14, 0 ), ( 1, 15, 1 ), ( 1, 16, 1 ), ( 1, 17, 0 ), ( 1, 18, 1 ), ( 1, 19, 1 ), ( 1, 20, 1 ), ( 1, 21, 1 ), ( 1, 22, 1 ), ( 1, 23, 0 ), ( 1, 24, 1 ), ( 1, 25, 1 ), ( 1, 26, 1 ), ( 1, 27, 0 ), ( 1, 28, 1 ), ( 1, 29, 1 ), ( 1, 30, 1 ), ( 1, 31, 1 ), ( 2, 0, 0 ), ( 2, 1, 1 ), ( 2, 2, 0 ), ( 2, 3, 0 ), ( 2, 4, 0 ), ( 2, 5, 0 ), ( 2, 6, 1 ), ( 2, 7, 0 ); select * @bits order id, position; extendedbits ( select id, position, value, position / 4 nibbleid, power( 2, 3 - position % 4 ) * value mask @bits ), nibbles ( select id, nibbleid, sum( mask ) nibble extendedbits group id, nibbleid ), hexstrings ( select id, stuff( ( select substring( '0123456789abcdef', nibble + 1, 1 ) nibbles id = n.id order nibbleid xml path( '' ) ), 1, 0, '' ) hexstring nibbles n group id ) select id, cast( '' xml).value('xs:hexbinary( substring(sql:column("hexstring"), 0) )', 'varbinary(max)') varbin hexstrings;
note can view intermediate results replacing final select
select * extendedbits
or nibbles
or hexstrings
. handy debugging technique.
Comments
Post a Comment