Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

tsql - What does "&" means in this sql where clause?

What does the "&" mean here:

select pt.TrTp, sum(pt.TrTp)
from ProdTr pt
where TransSt & 16 <> 16  // this is the row that i don′t understand..
group by pt.TrTp
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's called a bitmask. It is used in situations where the individual bits in a number have different meanings, as opposed to a number just meaning the number itself (for instance, if you save your age to the database).

When you imagine any number in it's binary form and want to test if a certain bit in the number is set, you test it by using the binary AND operator with the number and the bit you want to test, like this:

if (number & 16 == 16)

In binary, this means the following (assuming, your number is 25):

if (00011001 & 00010000 == 00010000)

Here you can see, that the digits at the bit 5 (counted from the bottom up) are both 1, therefor the resulting number has a 1 at that bit. As there are no other 1s, the resulting number is 16 exactly when both numbers have a 1 at this position.

I would like to add: It's usually bad practice to encode different meanings into one database field. It's difficult to index and retrieve by an index, and depending on your DBMS might even be completely unindexed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...