我希望在我的WHERE子句中有一个IF语句在我拥有的存储过程中。这就是我想要实现的目标:
SELECT * FROM Issues
WHERE
Issues.ProjectId = @projectId
and (Issues.MilestoneName IN('Milestone1, Milestone2, Milestone3')
OR Issue.MilestoneId IS NULL)
-- this works fine but i only want the OR to run if a condition is met like so
SELECT * FROM Issues
WHERE
Issues.ProjectId = @projectId
and (Issues.MilestoneName IN('Milestone1, Milestone2, Milestone3')
IF @milestoneStringInput IN('NULL')
BEGIN
OR Issue.MilestoneId IS NULL)
END
是否有可能实现这一目标?
答案 0 :(得分:2)
您可以直接在WHERE子句中引用变量,与
一样SELECT *
FROM Issues
WHERE
Issues.ProjectId = @projectId
and
(
Issues.MilestoneName IN ('Milestone1, Milestone2, Milestone3')
OR
(
Issue.MilestoneId IS NULL AND
@milestoneStringInput = 'NULL'
)
)
答案 1 :(得分:1)
SQL不允许条件逻辑,只允许条件表达式(link)。但是,您的情况不需要条件表达式,因为可以使用布尔逻辑表示相同的逻辑:
SELECT * FROM Issues
WHERE
Issues.ProjectId = @projectId
and (Issues.MilestoneName IN('Milestone1, Milestone2, Milestone3')
AND ((@milestoneStringInput != 'NULL') OR (Issue.MilestoneId IS NULL))
条件的逻辑在最后一行表示:当@milestoneStringInput != 'NULL'
时,条件变为TRUE
;另一方面,当@milestoneStringInput
为'NULL'
时,Issue.MilestoneId IS NULL
将会被检查。
答案 2 :(得分:1)
您的原始查询完全符合您的需要。记住SQL是一种非常文字的语言,它将按照您编写代码的顺序执行。如果符合Issues.ProjectId = @projectId
,则会转到您的AND语句。 OR Issue.MilestoneId IS NULL
执行的唯一方法是首先不满足Issues.MilestoneName IN('Milestone1, Milestone2, Milestone3')
。 OR语句说"嘿,执行一个或另一个,具体取决于首先满足的条件"。