我有这些桌子
用户
User_Id int PK, User_Name varchar(50)
页
Page_Id int PK, Page_Name varchar(50)
允许
Permission_Id int PK , User_Id int FK, Page_Id int FK,
Read bit, Write bit, Delete bit
要求:
- 根据提供的查询以从该页面的
Page
加号中选择全部。Read, Write, Delete
Permission
@User_Id
- 如果
@User_Id
未通过,则应使用null
in选择所有页面Read, Write, Delete
。 - 如果提供
@User_Id
的内容不存在,Permission
则应Read, Write, Delete
选择为null
. - 在某些情况下
permission
,某些但并非全部pages
与 a 相关联的记录可能会出现user
,在这种情况下,所有记录都pages
应该出现,并且对于那些没有关联的页面,user_id
应该null
在Read, Write, Delete
列中。
我所做的是这个
declare @User_Id int=null;
SELECT
page.Page_Name,
page.Page_Id,
isnull((select Read from Permission where
(@User_Id is null OR User_Id = @User_Id ) and
(Permission.Page_Id = Page.Page_Id)),0)
as Read,
isnull((select Write from Permission where
(@User_Id is null OR User_Id = @User_Id) and
(Permission.Page_Id = Page.Page_Id)),0)
as Write,
isnull((select Delete from Permission where
(@User_Id is null OR User_Id = @User_Id) and
(Permission.Page_Id = Page.Page_Id)),0)
as Delete,
isnull((select Export from Permission where
(@User_Id is null OR User_Id = @User_Id) and
(Permission.Page_Id = Page.Page_Id)), 0)
as Export
FROM Page
此查询工作正常并满足所有要求,但正如您所看到的sub queries
,我想消除它,一个选项可能是sql functions
,但我想知道是否有其他方法可以解决这个问题。