sql-server - 带有 CASE & NOT IN 条件的 SQL Where 子句
问题描述
我有一个带有 where 子句的选择查询。现在我必须根据用户访问在 where 子句中添加附加条件。如果用户无权访问,则需要在 where 子句中包含附加条件,否则如果用户有权访问,则没有附加逻辑。
例如:
Select * from TableA where ID > 100
附加逻辑:如果用户无权访问管理页面,则@X = 0,如果无权访问外部页面,则@Y = 0。
我需要在 where 子句中包含以下逻辑:
if (@X = 0 and @y=0) then
pagecode not in ('admin','external')
else if(@x=0 and @y=1) then
pagecode not in ('admin')
else if(@x=1 and @y=0) then
pagecode not in ('external')
else
no additional logic in where clause
如何在 where 子句中实现这个用例。
解决方案
您可以在 WHERE 中使用 CASE,如下所示:
WHERE 1=(
CASE WHEN @X = 0 and @y = 0 and pagecode not in ('admin','external') THEN 1
WHEN @x = 0 and @y = 1 and pagecode not in ('admin') THEN 1
WHEN @x = 1 and @y = 0 and pagecode not in ('external') THEN 1
ELSE 0 END
)
如果@x=1 和@y=1,这不会返回任何行。如果您想在@x=1 和@y=1 的情况下返回所有行
WHERE 1=(
CASE WHEN @X = 0 and @y = 0 and pagecode not in ('admin','external') THEN 1
WHEN @x = 0 and @y = 1 and pagecode not in ('admin') THEN 1
WHEN @x = 1 and @y = 0 and pagecode not in ('external') THEN 1
WHEN @x = 1 and @y = 1 THEN 1
ELSE 0 END
)
推荐阅读
- c# - 使用 HtmlFieldPrefix 将数据发布到操作会产生空模型
- php - 如何使用 htaccess 将 url 重定向到动态子域?
- reactjs - 如何从当前组件重定向到另一个组件,并将道具传递给 React 中的重定向组件
- javascript - 如何将 JavaScript 数组添加到 localStorage 以进行临时数据存储?
- python - 查找行组和列组 pandas 的平均值
- postgresql - 表“图像”上的更新或删除违反了外键约束
- android - 仅在切换方向水平垂直时才调用 onRestoreInstanceState - 还有其他情况吗?
- ios - 在ios上启动应用程序时如何请求权限?
- graphviz - GraphViz 保持图形位置一致
- excel - VBA 打印活动工作表增量