Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Data With BIT TYPE for SQL Server

Tags:

sql-server

I have a column using a BIT type (1/0). I have some records are set to 1 and some are set to 0. Those are record flag needs to be reversed. So basically, I want all records with 1 set 0, and all records with 0 set to 1.

If I run

Update Table1 Set Flag = 1 Where Flag = 0

first, then I am afraid all record flags will be 1 now, and will not able to know which ones are flag = 0.

Any suggestions?

Thanks!

like image 486
Milacay Avatar asked Jun 15 '26 09:06

Milacay


2 Answers

Here's a way you can do it without a CASE statement, using a bitwise operator instead:

update Table1
set flag = ~flag

Hope this helps!

like image 128
Andy Mudrak Avatar answered Jun 17 '26 23:06

Andy Mudrak


To negate the value of all bit fields do it in one operation. You can use a CASE

UPDATE table1
SET    flag = CASE flag
                WHEN 1 THEN 0
                WHEN 0 THEN 1
              END 

Or Bitwise Exclusive OR

UPDATE table1
SET    flag = flag ^ 1
like image 38
Martin Smith Avatar answered Jun 18 '26 00:06

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!