Given the following table:
CREATE TABLE BitValues ( n int )
Is it possible to compute the bitwise-OR of n
for all rows with
Are you looking for something like this?
EDIT: As noted in other comments, this answer was based on the assumption that the BitValues table would only contain powers of 2. I tried to read between the lines of the question and infer a use for the inline subquery.
declare @BitValues table (
n int
)
declare @TestTable table (
id int identity,
name char(10),
BitMappedColumn int
)
insert into @BitValues (n)
select 1 union all select 2 union all select 4
insert into @TestTable
(name, BitMappedColumn)
select 'Joe', 5 union all select 'Bob', 8
select t.id, t.name, t.BitMappedColumn
from @TestTable t
inner join (select SUM(n) as BitMask from @BitValues) b
on t.BitMappedColumn & b.BitMask <> 0
Your best bet for a readable and re-usable solution would be to write a a custom CLR Aggregate to perform bitwise or. A tutorial for creating this type of operation can be found here: http://msdn.microsoft.com/en-us/library/91e6taax(VS.80).aspx
I see this post is pretty old and there are some useful answers but this is a pretty crazy straight forward method...
Select
SUM(DISTINCT(n & 0x01)) +
SUM(DISTINCT(n & 0x02)) +
SUM(DISTINCT(n & 0x04))
as OrN
From BitValues
Preparations:
if object_id(N'tempdb..#t', N'U') is not null drop table #t;
create table #t ( n int );
insert into #t values (1), (2), (4), (3);
Solution:
select max(n & 8) + max(n & 4) + max(n & 2) + max(n & 1) from #t;