T-SQL 中 WHERE 子句中的多个 IF 子句

Vit*_*mir 1 sql t-sql sql-server if-statement

我有一个包含三列的表 #t1,其中一列名为root_symbol.

我想从 table #t1 中选择所有满足 variable 条件的元素@root

但是,变量@root可以有四个不同的值,因此我想where根据声明的变量值动态选择语句应用的过滤器。

declare @root integer
set @root = 1

select * from #t1
where root_symbol in
case when @root = 1 then ('ES')
        when @root = 2 then ('EW', 'EW1', 'EW2', 'EW3', 'EW4') 
        when @root = 3 then ('E1C', 'E2C', 'E3C', 'E4C', 'E5C') 
        when @root = 4 then ('E1A', 'E2A', 'E3A', 'E4A', 'E5A') 
end
Run Code Online (Sandbox Code Playgroud)

我已经看到使用case when,但不是使用值匹配条件完成的in

另一种方法是创建一个 if 语句,其中包含四个不同的 select 语句,但是在这里我也不确定如何处理 sql 中的多子句 if 语句。

知道如何解决这个问题吗?

Gor*_*off 6

不要使用case. 使用简单的比较:

where (@root = 1 and root_symbol in ('ES')) or
      (@root = 2 and root_symbol in ('EW', 'EW1', 'EW2', 'EW3', 'EW4')) or
      (@root = 3 and root_symbol in ('E1C', 'E2C', 'E3C', 'E4C', 'E5C')) or 
      (@root = 4 and root_symbol in ('E1A', 'E2A', 'E3A', 'E4A', 'E5A'))
Run Code Online (Sandbox Code Playgroud)

一般来说,casewhere子句中使用表达式是一个坏主意(有一些例外)。因为它case强制其子句的求值顺序,所以它阻止优化器做任何事情。