开发者

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

开发者 https://www.devze.com 2023-01-09 04:47 出处:网络
I\'m converting some data in SQL Server: 开发者_如何学PythonINSERT INTO MYTABLE (AllowEdit) (Select PreventEdit from SOURCETABLE)

I'm converting some data in SQL Server:

开发者_如何学Python
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?


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消