如何有条件地将AND条件添加到SQL Server

时间:2018-01-23 10:30:52

标签: sql sql-server

我有一个包含以下架构的表:

| ID | BUNDLE_ID | IS_ADMIN |

我需要根据某些标准从上表中选择具有AND子句的数据,即

IF @FLAG = 1
    SELECT * 
    FROM TABLE A 
    WHERE A.IS_ADMIN = 1 AND BUNDLE_ID IN (3, 5)
ELSE
    SELECT * 
    FROM TABLE A 
    WHERE A.IS_ADMIN = 1 AND BUNDLE_ID IN (1, 2)

我可以在一次查询中实现这一目标吗?

7 个答案:

答案 0 :(得分:3)

一般方法是使用布尔表达式重写查询,该表达式根据flag的值计算所需内容:

SELECT * FROM TABLE A WHERE A.IS_ADMIN = 1 AND ( -- Common part ...
    (@Flag=1  AND BUNDLE_ID IN(3,5))     -- IF   ...
OR
    (@Flag<>1 AND BUNDLE_ID IN(1,2))     -- ELSE ...
)

答案 1 :(得分:2)

是的,很简单。

SELECT *
FROM TABLE A
WHERE (A.IS_ADMIN = 1
        AND BUNDLE_ID IN (3,5)
        AND @FLAG = 1)
    OR (A.IS_ADMIN = 1
        AND BUNDLE_ID IN (1,2)
        AND (@FLAG <> 1 OR @FLAG IS NULL))

答案 2 :(得分:1)

简单地:

SELECT * 
FROM   TABLE A 
WHERE  (A.IS_ADMIN = 1 AND BUNDLE_ID IN(3,5) AND @FLAG = 1)
   OR  (A.IS_ADMIN = 1 AND BUNDLE_ID IN(1,2) AND (@FLAG <> 1 OR @FLAG IS NULL))

答案 3 :(得分:1)

您可以使用表驱动控件

SELECT A.* FROM TABLE A 
    INNER JOIN (VALUES (0,1),(0,2),(1,3),(1,5)) COND(FLAG,BUNDLE_ID)  
        ON A.BUNDLE_ID = COND.BUNDLE_ID
            AND COND.FLAG = ISNULL(@FLAG,0)
WHERE
    A.IS_ADMIN = 1  

答案 4 :(得分:1)

替代方案,仅仅因为......

SELECT * FROM a_table A WHERE @flag =  1 AND IS_ADMIN = 1 AND A.BUNDLE_ID IN (3, 5)
UNION ALL
SELECT * FROM a_table A WHERE @flag <> 1 AND IS_ADMIN = 1 AND A.BUNDLE_ID IN (1, 2)

应该给出类似的执行计划......

SELECT
  *
FROM
  a_table   AS A
CROSS APPLY
(
  SELECT A.BUNDLE_ID WHERE @flag =  1 AND A.BUNDLE_ID IN (3, 5)
  UNION ALL
  SELECT A.BUNDLE_ID WHERE @flag <> 1 AND A.BUNDLE_ID IN (1, 2)
)
WHERE
  A.IS_ADMIN = 1

与已提供的其他答案不同的布局,但提供相同的逻辑......

WITH
    admin AS
(
    SELECT * FROM a_table A WHERE IS_ADMIN = 1
)
SELECT
    *
FROM
    admin
WHERE
       (@flag =  1 AND BUNDLE_ID IN (3, 5))
    OR (@flag <> 1 AND BUNDLE_ID IN (1, 2))

答案 5 :(得分:0)

尝试:

SELECT * FROM TABLE A 
WHERE A.IS_ADMIN = 1 AND 
(BUNDLE_ID IN (3,5) AND @FLAG = 1) OR 
(BUNDLE_ID IN (1,2) AND @FLAG <> 1)

答案 6 :(得分:0)

这也是完全有效的语法......

IF @FLAG = 1
BEGIN
    SELECT * FROM TABLE A WHERE A.IS_ADMIN = 1 AND BUNDLE_ID IN(3,5)
END
ELSE
BEGIN
    SELECT * FROM TABLE A WHERE A.IS_ADMIN = 1 AND BUNDLE_ID IN(1,2)
END