user3428422
user3428422

Reputation: 4560

Find integer value using bitwise logic in SQL

I am migrating old data into a new database structure and I need to find out the total int of 3 BIT fields in SQL.

So for example,

(Col A = 1, Col B = 2, Col C = 4)

Col A, Col B, COL C
 0      0       0   = 0
 1      0       0   = 1 
 0      1       0   = 2
 0      0       1   = 4
 1      1       1   = 7

I have tried in SQL

SELECT Col A & 1, Col B & 2 

But not entirely sure if that logic will work..

Thanks in advance

Upvotes: 1

Views: 115

Answers (1)

StuartLC
StuartLC

Reputation: 107247

Just multiply the columns by their respective powers of 2. Assuming that ColA is the least significant bit:

SELECT ColA + ColB * 2 + ColC * 4 FROM MyTable;

SqlFiddle

Upvotes: 3

Related Questions