SQL Server存储过程,在CASE子句中的Else语句中返回多个值

时间:2012-06-13 06:48:31

标签: stored-procedures in-clause

我想在where子句

中使用CASE和IN子句
  • 当用户状态= 1时,CASE应返回1
  • 当用户状态= 2时,CASE应返回2
  • 当用户状态= 3时,CASE应返回3
  • 当User.Status = NULL时,它应显示状态为1,2和3的所有用户

但是下面的查询引发了语法错误。

QUERY:

SELECT *
FROM User
where isInternalUser = 0 and DeleteMark <> 1 and
User.Status IN 
(
   CASE @UserStatus          // case for UserStatus
       WHEN 0 THEN 0
       WHEN 1 THEN 1
       WHEN 2 THEN 2
       ELSE (0,1,2)           
    END                      
)

任何人都可以帮我解决..

谢谢, Aneesh

2 个答案:

答案 0 :(得分:1)

尝试不使用CASE语句,但要检查是否@UserStatus IS NULL

SELECT *
FROM User
WHERE isInternalUser = 0 AND DeleteMark <> 1 AND (
    (@UserStatus IS NOT NULL AND Status = @UserStatus)
    OR (@UserStatus IS NULL AND Status IN (0, 1, 2))
)

答案 1 :(得分:0)

User.Status IN 
(
    SELECT s FROM (
        SELECT 1 s union SELECT 2 s union SELECT 3 s
    ) a
    WHERE @UserStatus is null or @UserStatus = s
)