Is there an elegant way to Invert a Bit value in an SQL insert Statement?

Molloch picture Molloch · Jul 24, 2010 · Viewed 27.9k times · Source

I'm converting some data in SQL Server:

INSERT INTO MYTABLE (AllowEdit)
(Select PreventEdit from SOURCETABLE)

so I need to inverse the bit value from source table. I expected NOT to work, as this is how I would do it in code, but it doesn't. The most elegant way I can think of is:

INSERT INTO MYTABLE (AllowEdit)
(Select ABS(PreventEdit -1) from SOURCETABLE)

Is there a more standard way to do it?

Answer

driis picture driis · Jul 24, 2010

I did not test this myself, but you should be able to use the bitwise negation operator, ~ on a bit:

INSERT INTO MYTABLE (AllowEdit) 
(SELECT ~PreventEdit FROM SourceTable)