SQL Server WHERE 子句中的与号 (&) 运算符

2021-12-10 00:00:00 bitwise-operators tsql sql-server

抱歉问了一个非常基本的问题.& 操作符在这个 SQL 中有什么作用

Sorry for the very basic question. What does the & operator do in this SQL

WHERE (sc.Attributes & 1) = 0 

sc 是包含 attributes 列的表的别名.

sc is an alias for a table which contains a column attributes.

我试图理解报告中的一些 SQL,该行使其返回 0 个条目.如果我将其注释掉,它会起作用.我的 SQL 知识有限,我不确定 &1 正在做.

I'm trying to understand some SQL in a report and that line is making it return 0 entries. If I comment it out it works. I have limited SQL knowledge and I'm not sure what the & 1 is doing.

推荐答案

&是按位逻辑和运算符 - 它对 2 个整数值执行运算.

& is the bitwise logical and operator - It performs the operation on 2 integer values.

WHERE (sc.Attributes & 1) = 0 

以上代码检查 sc.Attributes 是否为偶数.这与说第一位未设置相同.

The above code checks to see if sc.Attributes is an even number. Which is the same as saying that the first bit is not set.

由于列的名称:属性",那么1"值可能只是一些具有某种外部含义的标志.

Because of the name of the column though: "Attributes", then the "1" value is probably just some flag that has some external meaning.

对于存储在属性数字中的每个标志,通常使用 1 个二进制数字.因此,要测试第一位,您使用 sc.Attributes&1,测试第二位您使用 sc.Attributes&2,测试第三位您使用 sc.Attributes&4,测试第四位您使用 sc.Attributes&8, ...

It is common to use 1 binary digit for each flag stored in a number for attributes. So to test for the first bit you use sc.Attributes&1, to test for the second you use sc.Attributes&2, to test for the third you use sc.Attributes&4, to test for the fourth you use sc.Attributes&8, ...

= 0 部分正在测试以查看第一位是否未设置.

The = 0 part is testing to see if the first bit is NOT set.

一些二进制示例:(== 显示运算结果)

Some binary examples: (== to show the result of the operation)

//Check if the first bit is set, same as sc.Attributes&1
11111111 & 00000001 == 1
11111110 & 00000001 == 0
00000001 & 00000001 == 1


//Check if the third bit is set, same as sc.Attributes&4
11111111 & 00000100 == 1
11111011 & 00000100 == 0
00000100 & 00000100 == 1

相关文章