我想添加一个执行以下操作的子句:
DECLARE @RequiresApproval BIT
SET @RequiresApproval = 0
SELECT * FROM [user] u
WHERE school_id = 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
答案 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