I have to admit, sometimes I struggle with what I visualise as the solution and map it in code, here is an example count the matching ON bits in 2 bitmasks, it should be a bitwise comparison and be lightning fast however to make it work I end up looping over a string array, kind of like the opposite of what I need to achieve when considering speed.
Here is the T-SQL code:
declare @p1Flags tinyint = 1|4|8|16, --> enum flags
@p2Flags tinyint = 1|4|16|32
print 'Person 1:'+ [Utilities].[ToBinaryString](@p1Flags)
print 'Person 2:'+ [Utilities].[ToBinaryString](@p2Flags)
declare @ix int =1,
@Person1 varchar(8) =reverse([Utilities].[ToBinaryString](@p1Flags)),
@Person2 varchar(8) =reverse([Utilities].[ToBinaryString](@p2Flags)),
@match bit =0,
@matched int=0;
--> compare only the range that can hold data
declare @lenPerson1 tinyint = len(@Person1) - Charindex('1',reverse(@Person1),0)+1
, @lenPerson2 tinyint = len(@Person2) - Charindex('1',reverse(@Person2),0)+1
while @ix <= @lenPerson1
begin
if @ix > @lenPerson2
break;
set @match= iif (SUBSTRING(@Person1,@ix,1)=SUBSTRING(@Person2,@ix,1) and SUBSTRING(@Person1,@ix,1)='1',1,0)
if @match=1 --> same interest
set @matched=@matched+1
set @ix= @ix+1
end;
declare @result decimal(7,4) = (1.*@matched)*100./(1.* @lenPerson1)
print '-------------------------------------------------------------------------'
print 'Matching bits in bitmap: '+ cast(@matched as varchar(2))+' of '+cast(@lenPerson1 as varchar(2))+ ' = ' +cast(@result as char(8)) +'%'
The generated test shows the result:
Person 1:00011101
Person 2:00110101
----------------------------------------------
Matching bits in bitmap: 3 of 5 = 60.0000 %
So, the concept works, now how to do it the right way?
Thanks for the help
Walter