SQL条件和子句

时间:2014-07-30 04:00:20

标签: sql sql-server

我想添加一个执行以下操作的子句:

DECLARE @RequiresApproval BIT
SET @RequiresApproval = 0
SELECT * FROM [user] u
WHERE school_id = 1

这是我想要的逻辑

  • 当@RequiresApproval = 1时,然后添加子句:AND approved = 1
  • 当@RequiresApproval = 0时,请忽略条款:AND approved = 1

我的目标是让SQL最终得到以下任何一种,具体取决于@RequiresApproval的值。这可能吗?

-- when @RequiresApproval = 1, use this
SELECT * FROM [user] u
WHERE school_id = 1


-- when @RequiresApproval = 0, use this
SELECT * FROM [user] u
WHERE school_id = 1
AND approved = 1

3 个答案:

答案 0 :(得分:6)

确定。这应该实现你的逻辑:

SELECT *
FROM [user] u
WHERE school_id = 1 AND
      (@RequiresApproval = 0 or approved = 1);

答案 1 :(得分:3)

您可以使用此查询 - 您只需在两个条件之间使用OR

SELECT * FROM [user] u
WHERE school_id = 1
AND (approved = 1 OR @RequiresApproval = 0)

答案 2 :(得分:0)

这也可以。

SELECT  * FROM  [user] u
WHERE   [school_id] = 1 AND [approved] = 1 
AND     @RequiresApproval = 1
UNION 
SELECT  * FROM  [user] u 
WHERE   [school_id] = 1 AND @RequiresApproval = 0