2013-04-02 283 views
0

我有一個存儲過程,看起來像:if語句的WHERE子句

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

感謝您的任何幫幫我。

羅布

回答

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)) 
) 
+0

謝謝,這很好用! – Robert

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)) 
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;