如何在 SQL Server 中稍微翻转一下?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/171173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I flip a bit in SQL Server?
提问by Even Mien
I'm trying to perform a bitwise NOT in SQL Server. I'd like to do something like this:
我正在尝试在 SQL Server 中按位执行 NOT。我想做这样的事情:
update foo
set Sync = NOT @IsNew
Note: I started writing this and found out the answer to my own question before I finished. I still wanted to share with the community, since this piece of documentation was lacking on MSDN (until I added it to the Community Content there, too).
注意:我开始写这篇文章并在我完成之前找到了我自己问题的答案。我仍然想与社区分享,因为 MSDN 上缺少这篇文档(直到我也将它添加到那里的社区内容中)。
回答by Jason Kresowaty
Yes, the ~ operator will work.
是的, ~ 运算符会起作用。
update foo
set Sync = ~@IsNew
回答by Even Mien
Bitwise NOT: ~
按位非:~
Bitwise AND: &
按位与:&
Bitwise OR: |
按位或: |
Bitwise XOR: ^
按位异或:^
回答by Blorgbeard is out
Lacking on MSDN? http://msdn.microsoft.com/en-us/library/ms173468(SQL.90).aspx
缺少 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.
~:对整数值执行按位逻辑非运算。~ 按位运算符对表达式执行按位逻辑非,依次取每一位。如果表达式的值为 0,则结果集中的位设置为 1;否则,结果中的位被清除为值 0。换句话说,1 变为 0,0 变为 1。
回答by Oliver
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
回答by vitik
~ operator will work only with BIT,
~ 操作员只能与 BIT 一起工作,
try: ~ CAST(@IsNew AS BIT)
尝试:~ CAST(@IsNew AS BIT)