How do I flip a bit in SQL Server?

SqlSql ServerBit Manipulation

Sql Problem Overview


I'm trying to perform a bitwise NOT in SQL Server. I'd like to do something like this:

update foo
set Sync = NOT @IsNew

Note: I started writing this and found out the answer to my own question before I finished. I still wanted to share with the community, since this piece of documentation was lacking on MSDN (until I added it to the Community Content there, too).

Sql Solutions


Solution 1 - Sql

Yes, the ~ operator will work.

update foo
set Sync = ~@IsNew

Solution 2 - Sql

Bitwise NOT: ~

Bitwise AND: &

Bitwise OR: |

Bitwise XOR: ^

Solution 3 - Sql

Lacking on MSDN? <http://msdn.microsoft.com/en-us/library/ms173468(SQL.90).aspx>

> ~: Performs a bitwise logical NOT operation on an integer value. The ~ bitwise operator performs a bitwise logical NOT for the expression, taking each bit in turn. If expression has a value of 0, the bits in the result set are set to 1; otherwise, the bit in the result is cleared to a value of 0. In other words, ones are changed to zeros and zeros are changed to ones.

Solution 4 - Sql

For the sake of completeness:

SELECT b, 1 - b
FROM
  (SELECT cast(1 AS BIT) AS b
   UNION ALL
   SELECT cast(0 AS BIT) AS b) sampletable

Solution 5 - Sql

~ operator will work only with BIT,

try: ~ CAST(@IsNew AS BIT)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEven MienView Question on Stackoverflow
Solution 1 - SqlJason KresowatyView Answer on Stackoverflow
Solution 2 - SqlEven MienView Answer on Stackoverflow
Solution 3 - SqlBlorgbeardView Answer on Stackoverflow
Solution 4 - SqlOliverView Answer on Stackoverflow
Solution 5 - SqlvitikView Answer on Stackoverflow