Ampersand (&) operator in a SQL Server WHERE Clause

有些话、适合烂在心里 提交于 2019-12-28 01:55:35

问题


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

WHERE (sc.Attributes & 1) = 0 

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

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.


回答1:


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

WHERE (sc.Attributes & 1) = 0 

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.

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

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, ...

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



回答2:


It's a bitwise and.




回答3:


It is a bitwise logical AND operator.




回答4:


Seeing as you tagged this as sql server, I thought I'd add something from a different angle as also ran into one of these this week.

These can hurt the performance of your queries if used in the predicate. Very easy to manufacture an example of your own. Here is the snippet from my query

WHERE
advertiserid = @advertiserid
AND (is_deleted & @dirty > 0)

WHERE
advertiserid = @advertiserid
AND (is_deleted > 0 AND @dirty > 0)

by simply defining each column with a proper value this allowed the optimizer to remove a bookmark lookup and performance stats showed a X10 performance increase.



来源:https://stackoverflow.com/questions/670230/ampersand-operator-in-a-sql-server-where-clause

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