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

落爺英雄遲暮 提交于 2019-12-03 00:53:56

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)

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

INSERT INTO MYTABLE (AllowEdit) (SELECT ~ISNULL(PreventEdit,0) FROM SourceTable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!