1

我有这些桌子

用户

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

要求:

  1. 根据提供的查询以从该页面的Page加号中选择全部。Read, Write, DeletePermission@User_Id
  2. 如果@User_Id未通过,则应使用nullin选择所有页面Read, Write, Delete
  3. 如果提供@User_Id的内容不存在,Permission则应Read, Write, Delete选择为null.
  4. 在某些情况下permission,某些但并非全部pages与 a 相关联的记录可能会出现user,在这种情况下,所有记录都pages应该出现,并且对于那些没有关联的页面,user_id应该nullRead, 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,但我想知道是否有其他方法可以解决这个问题。

4

1 回答 1

2

声明@User_Id int=null;

SELECT 
    page.Page_Name,
    page.Page_Id,
    ISNULL(Read,0) AS Read
    ISNULL(Write,0) AS Write,
    ISNULL(Delete,0) AS Delete,
    ISNULL(Export,0) AS Export
FROM 
    Page
    LEFT JOIN Permission ON Page.Page_ID = Permission.Page_ID AND Permission.User_ID = @User_ID

如果您也加入@userID 参数,那么当它为空时,它将与权限中的任何行都不匹配,因此您的值将为空

于 2012-10-08T13:08:37.923 回答