棘手的地方

时间:2013-03-10 21:52:57

标签: sql sql-server sql-server-2008 tsql

我不知道是不是我在一个漫长的一天的后端,或者我的编码器相当于作家阻止,但我想不出干净的方式这样做。

我有一个存储网页菜单结构的表,我想要一个简单的存储过程,它将根据Web应用程序中的会话参数返回相关的菜单项。

采用以下(简化)示例:

--#### Create example table
CREATE TABLE [dbo].[tbl_Page](
    [PageID] [int] IDENTITY(1,1) NOT NULL,
    [RequireLogin] [bit] NOT NULL,
    [RequireAdmin] [bit] NOT NULL,
    [HideIfLoggedIn] [bit] NOT NULL
)
GO

--#### Insert Dummy Data
SET IDENTITY_INSERT [dbo].[tbl_Page] ON
INSERT [dbo].[tbl_Page] ([PageID], [RequireLogin], [RequireAdmin], [HideIfLoggedIn]) VALUES (2, 1, 0, 0)
INSERT [dbo].[tbl_Page] ([PageID], [RequireLogin], [RequireAdmin], [HideIfLoggedIn]) VALUES (3, 1, 1, 0)
INSERT [dbo].[tbl_Page] ([PageID], [RequireLogin], [RequireAdmin], [HideIfLoggedIn]) VALUES (4, 0, 0, 1)
INSERT [dbo].[tbl_Page] ([PageID], [RequireLogin], [RequireAdmin], [HideIfLoggedIn]) VALUES (5, 0, 0, 0)
SET IDENTITY_INSERT [dbo].[tbl_Page] OFF

--#### Create menu procedure
CREATE PROCEDURE usp_GetSubMenu
    @ParentID INT ,
    @IsLoggedIn BIT ,
    @IsAdmin BIT
AS 
    BEGIN
        SET NOCOUNT ON;

        SELECT  PageID ,
                RequireLogin ,
                RequireAdmin ,
                HideIfLoggedIn
        FROM    tbl_Page
        WHERE ????????????
    END
GO

对于给定的示例数据,需要满足以下条件:

  1. 只有在@IsLoggedIn = 1
  2. 时才会列出网页ID 2
  3. 只有在@IsLoggedIn = 1 AND @IsAdmin = 1
  4. 时才会列出Page ID 3
  5. 页面ID 4应始终列出除非 @IsLoggedIn = 1(可能有页面需要登录用户(甚至是管理员用户)但仍需要隐藏 - 这是我大脑爆炸的地方......)
  6. 页面ID 5应该始终可见,无论用户是否登录,以及他们是否是管理员,因为它不需要登录,并且对于登录用户来说不是隐藏的

3 个答案:

答案 0 :(得分:2)

select PageID,
  RequireLogin,
  RequireAdmin,
  HideIfLoggedIn
from tbl_Page
where (HideIfLoggedIn <> @IsLoggedIn)
  and (RequireLogin = 0 or @IsLoggedIn = 1)
  and (RequireAdmin = 0 or @IsAdmin = 1)

适合我。

评论后编辑:

select PageID,
  RequireLogin,
  RequireAdmin,
  HideIfLoggedIn
from tbl_Page
where ((HideIfLoggedIn <> @IsLoggedIn)
  and (RequireLogin = 0 or @IsLoggedIn = 1)
  and (RequireAdmin = 0 or @IsAdmin = 1))
  or (RequireLogin = 0 and RequireAdmin = 0 and HideIfLoggedIn = 0)

我已更新查询以捕获您的上一个要求,并更新了以下SQL Fiddles:

显示@IsLoggedIn = 1, IsAdmin = 0 - PageID 2,5

SQL Fiddle

显示@IsLoggedIn = 1, IsAdmin = 1 - PageID 2,3,5

SQL Fiddle

SQL Fiddle显示@IsLoggedIn = 0, IsAdmin = 1 - PageID 4,5

答案 1 :(得分:1)

SELECT  PageID ,
            RequireLogin ,
            RequireAdmin ,
            HideIfLoggedIn
    FROM    tbl_Page
    WHERE 
   (@IsLoggedIn = 1 AND [HideIfLoggedIn] = 0) 
   AND [RequireLogin] = @IsLoggedIn
   AND [RequireAdmin] = @IsAdmin         

答案 2 :(得分:1)

我认为当where子句围绕负面...

构建时,这具有更好的可读性
SELECT 
    PageID,
    RequireLogin,
    RequireAdmin,
    HideIfLoggedIn
FROM 
    tbl_Page
WHERE 
    NOT
    (
       (HideIfLoggedIn = 1 AND @IsLoggedIn = 1)
       OR (RequireLogin = 1 AND @IsLoggedIn = 0)
       OR (RequireAdmin = 1 AND @IsAdmin = 0)
    )