SQL Server:IF中的Where子句.. ELSE

时间:2014-02-11 21:40:34

标签: sql sql-server stored-procedures

与已经解释过的标题一样,我在SQL存储过程中遇到了WHERE子句。

我有一个SELECT查询,它可以很好地连接多个表,如果得到一个WHERE子句,可以提供要搜索的特定值。

我的问题是,我想为2个不同的WHERE子句扩展此存储过程,但我无法使IF ELSE正确解析查询..

例如:

SELECT ....... 
FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE 
    man.Klant_ID = @Klant
    AND (@ManID = 0 OR man.ID = @ManID)
    AND .... (which continues like the rule above)

我希望得到这样的结论:

SELECT ....... 
FROM TABLE_X
INNER JOIN TABLE_Y.....

IF @TEMPVAR = ''
    WHERE man.Klant_ID=@Klant
    AND (@ManID = 0 OR man.ID = @ManID)
    AND... 
ELSE
    WHERE TABLE_X.ID IN (@TEMPVAR)

@tempvar应包含以逗号分隔的ID,如10001,10002,10003

我正在努力学习语法并搜索了一段时间,但似乎无法找到正确的解决方案。

提前致谢!

3 个答案:

答案 0 :(得分:4)

你可以用CASE来做到这一点:

SELECT ....... FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE TABLE_X.FIRSTCOLUMN = 
    CASE WHEN @TEMPVAR = '' THEN 123
         ELSE 456
    END

或直接在WHERE子句中加OR

WHERE (@TEMPVAR = ''
       AND man.Klant_ID=@Klant
       AND (@ManID = 0 OR man.ID = @ManID)
       AND... 
      ) 
      OR
      (@TEMPVAR <> '' 
       AND TABLE_X.ID IN (@TEMPVAR)
      )

答案 1 :(得分:2)

您可以使用where

中的直接逻辑执行此操作
SELECT ....... FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE TABLE_X.FIRSTCOLUMN = 123 and @TEMPVAR = '' or
      TABLE_X.FIRSTCOLUMN = 456 and @TEMPVAR <> ''

如果TEMPVAR可以是NULL,那么:

SELECT ....... FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE TABLE_X.FIRSTCOLUMN = 123 and @TEMPVAR = '' or
      TABLE_X.FIRSTCOLUMN = 456 and (@TEMPVAR <> '' or @TEMPVAR is null)

答案 2 :(得分:0)

另一种方法是:

IF @TEMPVAR = ''
SELECT ....... FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE TABLE_X.FIRSTCOLUMN = 123
    AND ....
ELSE
SELECT ....... FROM TABLE_X
INNER JOIN TABLE_Y.....
WHERE TABLE_X.FIRSTCOLUMN = 456
    AND ....