Is there a way of comparing two bitmasks in Transact-SQL to see if any of the bits match? I've got a User table with a bitmask for all the roles the user belongs to, and I'd like to select all the users that have any of the roles in the supplied bitmask. So using the data below, a roles bitmask of 6 (designer+programmer) should select Dave, Charlie and Susan, but not Nick.
User Table ---------- ID Username Roles 1 Dave 6 2 Charlie 2 3 Susan 4 4 Nick 1 Roles Table ----------- ID Role 1 Admin 2 Programmer 4 Designer
Any ideas? Thanks.
Best Solution
The answer to your question is to use the Bitwise
&
like this:The
6
can be exchanged for any combination of your bitfield where you want to check that any user has one or more of those bits. When trying to validate this I usually find it helpful to write this out longhand in binary. Your user table looks like this:Your test (6) is this
If we go through each person doing the bitwaise And against the test we get these:
The above should demonstrate that any records where the result is not zero has one or more of the requested flags.
Edit: Here's the test case should you want to check this
or
or