Ranjit Singh
Ranjit Singh

Reputation: 3735

Is there a way to do bitwise OR on any column using single query?

I am trying to find is there a way to calculate the bitwise OR of a column of a table using a single query. I can achieve the same using cursor

Declare @orValue int;
Declare @fieldValue int;

set @orValue = 0;

DECLARE my_cursor CURSOR FOR   
SELECT MyField  
FROM MyTable
WHERE SomeColumnValue=123

OPEN my_cursor  

FETCH NEXT FROM my_cursor   
INTO @fieldValue

WHILE @@FETCH_STATUS = 0  
BEGIN  
    set @orValue = @orValue | @fieldValue;
    FETCH NEXT FROM my_cursor  INTO @fieldValue
END   
CLOSE my_cursor;  
DEALLOCATE my_cursor; 

print @orValue;

Have done some google but didn't find any solution.

Upvotes: 0

Views: 80

Answers (1)

TT.
TT.

Reputation: 16137

DECLARE @orv INT = 0;

SELECT @orv=@orv|MyField
FROM MyTable
WHERE SomeColumnValue=123;

Upvotes: 5

Related Questions