在SQL Server中附加条件AND条件?

时间:2016-06-13 18:15:58

标签: sql sql-server sql-server-2008 sql-server-2012

我希望根据某些条件将AND条件附加到WHERE子句。以下是我面临的情况

DECLARE
    @param1 INT, @param2 INT

SET @param1 = 1
SET @param2 = 1

SELECT *
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.a = t2.b
INNER JOIN TABLE Table3 t3 ON t3.c = t2.d
WHERE t1.id = 1
  AND t2.id = 2

这是我希望条件进入的地方 -

Case when `@param1 = 1` and `@param2 = 1` THEN `AND t3.id = 4`

但我想这并不是这样的吗? :/为此有任何解决方法吗?

3 个答案:

答案 0 :(得分:2)

只需将其添加到where子句

即可

and isnull(t3.id,'') = case when @param1 = 1 and @param2 = 1 then 4 else isnull(t3.id,'') end

答案 1 :(得分:1)

我会把它写成:

where t1.id = 1 and t2.id = 2 and
      ((@param1 = 1 and @param2 = 1 and t3.id = 4) or
       not (@param1 = 1 and @param2 = 1)
      )

这确实假设参数不是NULL

答案 2 :(得分:0)

您可以将以下内容添加为AND条件,以检查t3.id = 4@param1何时@param2等于1,或者如果他们没有其他条件别' T:

SELECT *
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.a = t2.b
INNER JOIN Table3 t3 ON t3.c = t2.d
WHERE 
    t1.id = 1
    AND t2.id = 2
And
(
    (
        @param1 = 1
    And @param2 = 1
    And t3.id = 4
    )
    Or
    (
        @param1 <> 1
    Or  @param2 <> 1
    )
)