How do I flip a bit in SQL Server?
Asked Answered
B

5

90

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).

Bangtail answered 4/10, 2008 at 23:21 Comment(2)
I read this wrong I think...was gonna tell you that you can't make a Uturn in SQL Server...:PTitus
Another article: blogs.lessthandot.com/index.php/DataMgmt/DBProgramming/…Bangtail
I
135

Yes, the ~ operator will work.

update foo
set Sync = ~@IsNew
Incite answered 4/10, 2008 at 23:40 Comment(0)
B
35

Bitwise NOT: ~

Bitwise AND: &

Bitwise OR: |

Bitwise XOR: ^

Bangtail answered 4/10, 2008 at 23:21 Comment(0)
I
12

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.

Ignoramus answered 4/10, 2008 at 23:37 Comment(1)
D'oh. I just looked under bitwise operators and ~ unary operators :)Bangtail
B
2

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
Brunhilde answered 6/8, 2013 at 16:27 Comment(0)
V
2

~ operator will work only with BIT,

try: ~ CAST(@IsNew AS BIT)

Vaunting answered 11/7, 2019 at 19:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.