首页 > 解决方案 > 带有 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 子句中实现这个用例。

标签: sql-server

解决方案


您可以在 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
            )

推荐阅读