在SQL中的case语句中返回条件(在运算符中)

时间:2016-02-19 04:38:45

标签: sql sql-server

showProfilePic()

我的意思是如果“code = null”,查询将是这样的:

declare @code varchar(1)
set @code = null

select 
    *
from 
    Employee
where
    Emp_Id in  
    (
    case 
        when @code = null then 1,2,3
        then @code = 1 then 1,3
        when @code = 2 then 2,3
    end
    )

如果“code = 1”,查询将如下所示:

select 
    *
from 
    Employee
where
    Emp_Id in (1,2,3)

我不想像OR一样使用其他运算符,需要使用IN运算符。 有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您无法从case返回列表类型,但您可以执行此操作:

select *
from Employee
where (
    (@code is null and Emp_Id in (1,2,3)) or
    (@code = 1 and Emp_Id in (1,3)) or
    (@code = 2 and Emp_Id in (2,3))
)

另请注意,您的尝试包括when @code = null,这绝不是真的 - 在测试is null(而不是null)时,您必须使用= null

答案 1 :(得分:0)

动态-SQL:

declare @code varchar(1)
      , @sql nvarchar(max)

set @code = null

set @sql = N'
select *
  from Employee
  where Emp_Id in  (' + 
    case 
        when @code is null then '1,2,3'
        when @code = 1 then '1,3'
        when @code = 2 then '2,3'
    end +
    ')'

exec sp_executesql @sql
相关问题