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

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?


Solution 1:

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)

Solution 2:

NOT or XOR if bit

SELECT ~PreventEdit FROM SourceTable
SELECT 1 ^ PreventEdit FROM SourceTable

If it isn't actually bit in SourceTable then this:

SELECT 1 - PreventEdit FROM SourceTable

Edit: A test, note NOT is 2s complement so could give odd results if not used on a bit column

DECLARE @bitvalue bit = 1, @intvalue int = 1;

SELECT ~@bitvalue, ~@intvalue
SELECT 1 ^ @bitvalue, 1 ^ @intvalue
SELECT 1 - @bitvalue, 1 - @intvalue

SELECT @bitvalue = 0, @intvalue = 0

SELECT ~@bitvalue, ~@intvalue
SELECT 1 ^ @bitvalue, 1 ^ @intvalue
SELECT 1 - @bitvalue, 1 - @intvalue