3

我不知道是因为我在漫长的一天中处于落后状态,还是我的编码器相当于作家的障碍,但我想不出一种干净的方法来做到这一点。

我有一个存储网页菜单结构的表,我想要一个简单的存储过程,它将根据 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. 只有在以下情况下才应列出页面 ID 2@IsLoggedIn = 1
  2. 页面 ID 3 仅应在@IsLoggedIn = 1 AND时列出 @IsAdmin = 1
  3. 页面 ID 4 应该一直列出,除非 @IsLoggedIn = 1(很可能有些页面需要登录用户(甚至是管理员用户)但仍然需要隐藏 - 这是我的大脑爆炸的地方......)
  4. 页面 ID 5 应该始终可见,无论用户是否登录以及他们是否是管理员,因为它不需要登录并且对于已登录的用户不会隐藏
4

3 回答 3

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:

SQL Fiddle for @IsLoggedIn = 1, IsAdmin = 0- PageID 2,5显示。

SQL Fiddle for @IsLoggedIn = 1, IsAdmin = 1- PageID 2,3,5显示。

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

于 2013-03-10T22:10:47.360 回答
1
SELECT  PageID ,
            RequireLogin ,
            RequireAdmin ,
            HideIfLoggedIn
    FROM    tbl_Page
    WHERE 
   (@IsLoggedIn = 1 AND [HideIfLoggedIn] = 0) 
   AND [RequireLogin] = @IsLoggedIn
   AND [RequireAdmin] = @IsAdmin         
于 2013-03-10T22:11:05.673 回答
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)
    )
于 2013-03-11T00:05:19.820 回答