Ric_hc
Ric_hc

Reputation: 289

How to split a dynamic string in rows (right to Left)

This query converts dynamic int to binary, but I want to split into rows.

declare @value int 
set @value = 96

declare @result varchar(32) 
set @result = '' 

while 1 = 1 
begin
    select 
        @result = convert(char(1), @value % 2) + ',' +@result,
        @value = convert(int, @value / 2) 

    if @value = 0 break  
end

select substring(@result, 1, len(@result)-1) as result

Please help me to find a solution.

This is the result of my query.

1,1,0,0,0,0,0

My question is: how can I split this result into rows from right to left?

My result will need to be this (I'm trying to insert into a #table):

0
0
0
0
0
1
1

Thanks

Upvotes: 0

Views: 278

Answers (1)

Thom A
Thom A

Reputation: 95830

Using a WHILE seems like a really bad idea. If you want to achieve what you have this would be a far faster solution:

DECLARE @I int = 96

SELECT CONVERT(bit,@i & V.b)
FROM (VALUES(1),(2),(4),(8),(16),(32),(64)) V(b)
ORDER BY V.b;

Upvotes: 3

Related Questions