Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
T-SQL中WHERE子句中的多个IF子句_Sql_Sql Server_Tsql_If Statement - Fatal编程技术网

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

T-SQL中WHERE子句中的多个IF子句,sql,sql-server,tsql,if-statement,Sql,Sql Server,Tsql,If Statement,我有一个包含三列的表t1,其中一列名为root_symbol 我想从表t1中选择满足变量@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',

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

我想从表t1中选择满足变量@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
我在case-when中看到了这一点,但是没有使用中的值匹配条件

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

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

不要使用用例。使用简单的比较:

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'))
一般来说,where子句中的用例表达式是个坏主意,但也有一些例外。因为case强制其子句的求值顺序,所以它阻止优化器做任何事情。

不要使用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'))
一般来说,where子句中的用例表达式是个坏主意,但也有一些例外。因为case强制其子句的求值顺序,所以它阻止优化器执行任何操作。

T-SQL中的case是一个类似于a+b的表达式,它只能返回一个原子值-其他什么都不能-没有值列表或您在这里尝试执行的任何操作…T-SQL中的case是一个类似于a+b的表达式,它只能返回一个原子值,原子值-没有其他-没有值列表或任何您试图在这里执行的操作。。。