The loop-free option is a purely set-based approach (with a recursive CTE) and therefore should be quite efficient compared to any type of loop. You can use this function to connect or apply it to other data sets (tables or views)
-- function to split binary string to result-set alter function [dbo].[SplitStringToResultSet] (@value varchar(max), @size int) returns table as return with r as ( select right(value, 1) [bit] , left(value, len(value)-1) [value] , 0 [pos] from (select rtrim(cast( case when len(@value) > @size then left(@value, @size) when len(@value) < @size then @value + replicate('0', @size - len(@value)) else @value end as varchar(max))) [value]) as j union all select right(value, 1) , left(value, len(value)-1) , pos + 1 from r where value > '') select cast([bit] as int) [bit], [pos] from r -- usage ------------------------------------------------- declare @OR varchar(20) = '', @AND varchar(20) = ''; select @OR = @OR + cast(n1.[bit] | n2.[bit] as varchar(1)) , @AND = @AND + cast(n1.[bit] & n2.[bit] as varchar(1)) -- XOR etc from [dbo].[SplitStringToResultSet] ('11001100', 8) n1 full join [dbo].[SplitStringToResultSet] ('00100110', 8) as n2 on n1.[pos] = n2.[pos] order by n1.pos desc select @OR [OR], @AND [AND]
Result
OR AND -------------------- 11101110 00000100
source share