How to flip bit fields in T-SQL?

I'm trying to flip a bit in SQL Server using an update request, that is, I want to do all 0 in 1 and vice versa. What is the most elegant solution?

There seems to be no bitwise NOT operator in T-SQL (unless I see something obvious), and I could not find another way to perform the update.

+48
sql sql-server tsql
Sep 09 '09 at 3:00
source share
8 answers

You do not need bitwise - not for this - just XOR it with 1 / true.

To check this:

select idColumn, bitFieldY, bitFieldY ^ 1 as Toggled from tableX 

To update:

 update tableX set bitFieldY = bitFieldY ^ 1 where ... 

MSDN T-SQL Exclusive-OR (^)

+89
Sep 09 '09 at 3:10
source share

Why not just bitfield = 1 - bitfield ?

+39
Sep 09 '09 at 5:00
source share

Another way -

 DECLARE @thebit bit = 1, @theflipbit bit SET @theflipbit = ~ @thebit SELECT @theflipbit 

where "~" means the operator "NOT". It is clean and you get good code to read. β€œdeny bit" is even cleaner, and it does exactly what the NOT operator was designed for.

+15
Jun 18 '15 at 20:34
source share

I was sure that most of the SQL versions were bitwise, so I checked and there seems to be one of TSQL .

From the documentation, this is the ~ character.

+11
Sep 09 '09 at 3:03
source share
 UPDATE tblTest SET MyBitField = CASE WHEN MyBitField = 1 THEN 0 ELSE 1 END 

This is mild, but everyone will understand what he is doing.

EDIT:

You may also need to consider zeros, as suggested in the comments. Depends on your requirement, of course.

 UPDATE tblTest SET MyBitField = CASE WHEN MyBitField = 1 THEN 0 WHEN MyBitField = 0 THEN 1 ELSE NULL -- or 1 or 0 depending on requirements END 
+8
Sep 09 '09 at 3:18
source share

The simple bitwise NOT (~) operator worked for me in SQL Server 2014 - 12.0.2269.0

In the update clause inside your T-SQL -

  Update TableName SET [bitColumnName] = ~[bitColumnName], .... WHERE .... 

Hope this helps

Ref - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-not-transact-sql

+2
Jun 15 '17 at 9:58 on
source share

Have you tried this?

 UPDATE mytable SET somecolumn = CASE WHEN somecolumn = 0 THEN 1 WHEN somecolumn IS NULL THEN NULL WHEN somecolumn = 1 THEN 0 END 
0
Sep 09 '09 at 3:21
source share

query (vb)

 x = "select x from table" 

update (vb)

 "update table set x=" Not(x*(1)) 
0
Aug 01 '16 at 5:44
source share



All Articles