我不知道是不是我在一个漫长的一天的后端,或者我的编码器相当于作家阻止,但我想不出干净的方式这样做。
我有一个存储网页菜单结构的表,我想要一个简单的存储过程,它将根据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
对于给定的示例数据,需要满足以下条件:
@IsLoggedIn = 1
@IsLoggedIn = 1
AND @IsAdmin = 1
@IsLoggedIn = 1
(可能有页面需要登录用户(甚至是管理员用户)但仍需要隐藏 - 这是我大脑爆炸的地方......)答案 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 的
显示@IsLoggedIn = 1, IsAdmin = 1
- PageID
2,3,5 的
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)
)