IF声明在WHERE条款中

时间:2013-04-02 01:55:56

标签: sql sql-server

我有一个看起来像的小狗:

-- @intUserType int (Passed in from sproc)

IF @intUserType = 1
BEGIN
    SELECT * FROM Users
    WHERE Users.isDeleted = 0
END

IF @intUserType = 4
BEGIN
    SELECT * FROM Users
    WHERE Users.isDeleted = 0
    AND Users.UserType <> 1
END

IF @intUserType = 3
BEGIN
    SELECT * FROM Users
    WHERE Users.isDeleted = 0
    AND Users.UserType IN (1,3,4)
END

我想缩短它,不要使用这么多的select语句,有点像:

SELECT * FROM Users
WHERE Users.isDeleted = 1
AND
    IF @intUserType = 1
        THEN Users.UserType > 0
    ELSE IF @intUserType = 4
        THEN Users.UserType <> 1
    ELSE IF @intUserType = 3
        THEN Users.UserType NOT IN(1,3,4)
    END
END

感谢您的帮助。

罗布

3 个答案:

答案 0 :(得分:6)

SELECT * FROM Users
WHERE Users.isDeleted = 0 AND
( 
   (@intUserType = 1) OR
   (@intUserType = 4 AND Users.UserType <> 1) OR 
   (@intUserType = 3 AND Users.UserType IN (1,3,4))
)

答案 1 :(得分:5)

SELECT * FROM Users
WHERE @intUserType = 1 AND Users.isDeleted = 0
  OR (@intUserType = 4 AND Users.isDeleted = 0 AND Users.UserType <> 1)
  OR (@intUserType = 3 AND Users.isDeleted = 0 AND Users.UserType IN (1,3,4))

答案 2 :(得分:0)

这是另一种方法,只是为了完整性。您可以构建一个CASE函数来评估WHERE子句中的多个表达式:

SELECT * 
FROM Users
WHERE 
   CASE 
      WHEN @intUserType = 1 AND Users.isDeleted = 0 THEN 1
      WHEN @intUserType = 4 AND Users.isDeleted = 0 AND Users.UserType <> 1 THEN 1
      WHEN @intUserType = 3 AND Users.isDeleted = 0 AND Users.UserType IN (1,3,4) THEN 1
      ELSE 0
   END = 1;