0

我有一个看起来像这样的存储过程:

-- @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 * 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

谢谢你的帮助。

4

3 回答 3

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))
)
于 2013-04-02T01:59:08.967 回答
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))
于 2013-04-02T01:57:28.573 回答
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;
于 2013-04-02T03:03:53.377 回答