我假设您的 Permissions 列是一个 Int。如果是这样,我鼓励您使用我在下面提供的示例代码。这应该可以让您清楚地了解该功能的工作原理。
Declare @Temp Table(Permission Int, PermissionType VarChar(20))
Declare @CanRead Int
Declare @CanWrite Int
Declare @CanModify Int
Select @CanRead = 1, @CanWrite = 2, @CanModify = 4
Insert Into @Temp Values(@CanRead | @CanWrite, 'Read,write')
Insert Into @Temp Values(@CanRead, 'Read')
Insert Into @Temp Values(@CanWrite, 'Write')
Insert Into @Temp Values(@CanModify | @CanWrite, 'Modify, write')
Insert Into @Temp Values(@CanModify, 'Modify')
Select *
From @Temp
Where Permission & (@CanRead | @CanWrite) > 0
Select *
From @Temp
Where Permission & (@CanRead | @CanModify) > 0
当您使用逻辑与时,您将根据您的条件得到一个适当设置为 1 的数字。如果不匹配,则结果为 0。如果匹配 1 个或多个条件,则结果将大于 0。
让我给你看一个例子。
假设 CanRead = 1、CanWrite = 2 和 CanModify = 4。有效组合为:
Modify Write Read Permissions
------ ----- ---- -----------
0 0 0 Nothing
0 0 1 Read
0 1 0 Write
0 1 1 Read, Write
1 0 0 Modify
1 0 1 Modify, Read
1 1 0 Modify, Write
1 1 1 Modify, Write, Read
现在,假设您要测试读取或修改。从您的应用程序中,您将传入 (CanRead | CanModify)。这将是 101(二进制)。
首先,让我们针对 ONLY 读取的表中的一行进行测试。
001 (Row from table)
& 101 (Permissions to test)
------
001 (result is greater than 0)
现在,让我们针对只有 Write 的行进行测试。
010 (Row from table)
& 101 (Permission to test)
------
000 (result = 0)
现在针对具有所有 3 个权限的行对其进行测试。
111 (Row from table)
& 101 (Permission to test)
------
101 (result is greater than 0)
我希望您能看到,如果 AND 操作的结果是 value = 0,那么测试的权限都不会应用于该行。如果该值大于 0,则至少存在一行。