CREATE TABLE Users
(
UserId int,
UserName nvarchar(15),
Permissions int
)
CREATE TABLE Permissions
(
PermissionId int,
Title NVARCHAR(15)
)
我有这个数据的Permissions
表:
Id Title
--------------
1 'Read'
2 'Write'
4 'Update'
8 'Delete'
和Users
表
Id UserName Permission
-----------------------------------
1 'David' 3
2 'Sara' 8
3 'Maryam' 15
在这种情况下,'大卫'有'读'和'写'访问权限(1+2=3)
,'萨拉'萨拉只有'删除'访问权限(8)
和'Maryam'有'读','写' ','更新'和'删除'访问权限(1+2+4+8=15)
如何知道David有“读取”和“写入”权限,或者Sara只有“删除”权限?
这样的东西,但是在一个查询中
with CTE as
(
select a.Title, a.id + b.id as p_level
from p a
cross join p b
)
select u.*, p.*
from u u
inner join CTE p on u.permission = p.p_level
where u.id = 1
IF @@ROWCOUNT = 0
BEGIN
with CTE as
(
select p.*, sum(id) over (order by id) as p_level
from p
)
select u.*, p.*
from u
inner join CTE p
on u.permission >= p.p_level WHERE u.id=1
END
输出(id = 1
时):“David有读写权限”1 + 2 = 3
1 DAvid 3 Read 3
1 DAvid 3 Write 3
输出(当id = 2
时):“Sara只有删除访问权限”8
2 Sara 8 Update 8
答案 0 :(得分:4)
您可以使用join
:
select u.userId, p.title
from users u join
permissions p
on (u.permission & p.id) > 0;
这会将值放在不同的行中。
您可以使用诀窍将其作为列表获取:
select u.*,
stuff( (select ',' + p.title
from permissions p
where (p.id & u.permission) > 0
for xml path ('')
), 1, 1, ''
) as permissions
from users u;
答案 1 :(得分:2)
Select U.UserId , P.PermissionId
From #Users As U
Inner join
#Permissions As P
On P.PermissionId % U.Permisions >= 1
Where U.Permisions - P.PermissionId > 0