WHERE子句中的SQL IF语句

时间:2014-06-05 15:30:52

标签: sql-server stored-procedures

我希望在我的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

是否有可能实现这一目标?

3 个答案:

答案 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语句说"嘿,执行一个或另一个,具体取决于首先满足的条件"。