要获取设置为 1 和设置为 4 的所有行...
SELECT * FROM UserTable
WHERE userType & 5 = 5
要获取至少设置了 1 或 4 之一的所有行...
SELECT * FROM UserTable
WHERE userType & 5 <> 0
当然我们可以将它与连接结合起来:
SELECT Projects.*
FROM Projects JOIN UserTable
ON userID = UserTable.id
WHERE userType & 5 <> 0
或者加入旗帜。其中 PermissionSets 包含标志并且用户必须全部设置:
SELECT UserTable.*
FROM UserTable JOIN PermissionSets
ON UserTable.userType & PermissionSets.userType = PermissionSets.userType
WHERE PermissionSets.id = 42
其中 PermissionSets 包含标志且用户必须拥有一组:
SELECT UserTable.*
FROM UserTable JOIN PermissionSets
ON UserTable.userType & PermissionSets.userType <> 0
WHERE PermissionSets.id = 42
为 id 为 93 的用户打开SuperUser 位
UPDATE UserTable
SET userType = userType | 4
WHERE id = 93
为 id 为 93 的用户关闭 SuperUser 位
UPDATE UserTable
SET userType = userType & ~4
WHERE id = 93
从用于从 C# 处理此问题的 ADO.NET(或其他)代码中,我们可以将转换为 int 的相关 UserType 值传递到参数中,而不是显式发送 4 或 5。
编辑:另见Bitwise Operators (Transact-SQL)