views:

1147

answers:

2

I have a bitmasked int field in my database. Usually I manage it through c# code, but now I need to flip a bit in the mask using T-SQL

How do I accomplish the following:

The bit i want to flip: 1 << 8 (256)

The mask value before i flip: 143

The mask value after i flip: 399

I'm not exactly a bit-flipping wizard but this can be done without the bit operators that's missing in tsql, right?

+7  A: 

Use XOR:

SELECT value ^ 256

So in your case, SELECT 143 ^ 256 will indeed return 399. If you want to pass in the exponent as well:

SELECT value ^ POWER(2, power)
David M
thanks! It solved my problem! Is there also a way to turn on the bit in an elegant way? (i already did it, but it looks ugly...)
Christian Dalager
Are you looking to flip or turn on? Flip - use XOR (^); turn on - use OR (|). If you want more elegance, wrap in a tersely named user-defined function. :)
David M
+2  A: 

TSql Bitwise operators can be found here and good article on how to use them is here

Charles Bretana