基于三个表创建视图,其中列为表

时间:2015-08-05 10:54:31

标签: sql sql-server view pivot

我开始学习SQL,了解视图。 我想知道是否可以在一个视图中连接三个表,其中一些列将基于这些表中的行。

我有三张桌子:

角色:

Id | Name  | PermissionId
1  | Admin | 1
2  | Staff | 2

RolePermissions:

Id | RoleId | PermissionId
1  | 1      | 1
2  | 1      | 2
3  | 1      | 3
4  | 2      | 1
5  | 2      | 2      <- staff doesn't have permission 3

权限:

Id | Name
1  | Perm1
2  | Perm2
3  | Perm3
.
. (not fixed number of permissions)

我想创建这样的视图:

Id (of role) | Name  | Perm1 | Perm2 | Perm3  ... (not fixed number of columns)
1            | Admin | True  | True  | True
2            | Staff | True  | True  | False

有可能吗?

1 个答案:

答案 0 :(得分:1)

如果您不知道要输出的列数,则无法使用视图。 下面的代码应该是您正确的方向。如果需要动态构建列列表

,请在具有动态SQL的过程中使用它
; With roles(Id, Name, PermissionID) as (
Select * From (values(1, 'Admin', '1'), (2, 'Staff', '2')) as r(Id, Name, PermissionId)
), RolePermissions(Id, RoleId, PermissionId) as (
Select * From (Values(1, 1, 1), (2, 1, 2), (3, 1, 3), (4, 2, 1), (5, 2, 2)) as p(Id, RoleId, PermissionId)
), Permissionss(Id, Name) as (
Select * From (Values(1, 'Perm1'), (2, 'Perm2'), (3, 'Perm3')) as p(Id, Name)
), data as(
Select r.Id, rp.PermissionId, p.Name From Roles as r
Inner Join RolePermissions as rp on rp.RoleId = r.Id
Inner Join Permissionss as p on rp.PermissionId = p.Id
)
Select piv.Id as [Id of Role], r.Name
, [Perm1] = case when [Perm1] is not null then 'true' else 'false' end
, [Perm2] = case when [Perm2] is not null then 'true' else 'false' end
, [Perm3] = case when [Perm3] is not null then 'true' else 'false' end
From data
Pivot( max(PermissionId)
For Name in ( [Perm1], [Perm2], [Perm3])
) as piv
Inner Join roles as r on r.Id = Piv.Id