如何在 SQLServer 中翻转一点?

我试图在 SQL Server 中执行一个按位的 NOT:

update foo
set Sync = NOT @IsNew

注意: 我开始写这个,并找到了我自己的问题的答案之前,我完成了。我仍然想与社区分享,因为 MSDN 上缺少这个文档(直到我把它也添加到社区内容中)。

28971 次浏览

Bitwise NOT: ~

Bitwise AND: &

Bitwise OR: |

Bitwise XOR: ^

Lacking on MSDN? http://msdn.microsoft.com/en-us/library/ms173468(SQL.90).aspx

~: Performs a bitwise logical NOT operation on an integer value. The ~ bitwise operator performs a bitwise logical NOT for the expression, taking each bit in turn. If expression has a value of 0, the bits in the result set are set to 1; otherwise, the bit in the result is cleared to a value of 0. In other words, ones are changed to zeros and zeros are changed to ones.

Yes, the ~ operator will work.

update foo
set Sync = ~@IsNew

For the sake of completeness:

SELECT b, 1 - b
FROM
(SELECT cast(1 AS BIT) AS b
UNION ALL
SELECT cast(0 AS BIT) AS b) sampletable

~ operator will work only with BIT,

try: ~ CAST(@IsNew AS BIT)