简体   繁体   English

SQL Server与CASE一起使用

[英]Sql Server WHERE IN with CASE

How can we specify range of values from CASE inside WHERE clause? 我们如何在WHERE子句中从CASE指定值的范围?
This query of mine fails 我的此查询失败

declare @ProductType int

select * from Products 
where ProductLine in 
(
    case @ProductType
        when 1 then ('TVs')
        when 2 then ('Handsets', 'Mobiles') --fails here
        else ('Books')
    end
)

This wouldn't work either: 这也不起作用:

declare @ProductType int

select * from Products 
where (case @ProductType 
             when 1 then (ProductLine = 'TVs')
             when 2 then (ProductLine in  ('Handsets', 'Mobiles'))
             else (ProductLine = 'Books')
       end)

You cannot do that - you need to split it to several checks: 您无法做到这一点-您需要将其拆分为几项检查:

WHERE (ProductLine = 'TVs' AND @ProductType = 1)
   OR (ProductLine IN ('Handsets', 'Mobiles') AND @ProductType = 2)
   OR (ProductLine = 'Books' AND @ProductType NOT IN (1, 2))

There are two approaches you can take with this one. 您可以采用两种方法。 My first option would be to use a sub-query or common table expression to invert the logic and return the product type, and then match on product type. 我的第一个选择是使用子查询或通用表表达式来反转逻辑并返回产品类型,然后匹配产品类型。 The second would be to use 'sp_executesql'. 第二个是使用“ sp_executesql”。

First option: 第一种选择:

declare @ProductType int

WITH cte (Product_key, ProductType) AS (
    SELECT Product_key, CASE WHEN ProductLine IN ('TVs') THEN 1
        WHEN ProductLine IN ('Handsets', 'Mobiles') THEN 2  
        ELSE 3 END FROM Products
)
select p.* from Products p, cte 
where p.product_key = cte.product_key AND cte.ProductType = @ProductType

Second option: 第二种选择:

declare @ProductType int, @sql NVARCHAR(MAX)

SET @sql = 'select * from Products 
    where ProductLine in (' +
        case @ProductType
            when 1 then '''TVs'''
            when 2 then '''Handsets'', ''Mobiles'''
            else '''Books'''
        end + ')'
EXEC sp_executesql @sql
declare @ProductType int

select * from Products 
where (case @ProductType 
             when 1 then ProductLine in ('TVs') 
             when 2 then ProductLine in  ('Handsets', 'Mobiles') 
             else ProductLine in ('Books') end)

CASE is an expression that returns a value. CASE是一个返回值的表达式。 IN is a clause that may be part of a query. IN是可能是查询一部分的子句。 And SQL Server only grudgingly supports a boolean data type. 而且SQL Server只勉强支持布尔数据类型。

You can combine them thusly: 您可以这样组合它们:

declare @ProductType int = 1
declare @Products as Table ( ProductLine VarChar(16) )
insert into @Products ( ProductLine ) values ( 'TVs' ), ( 'Books' )
select *
  from @Products  
  where
    case @ProductType 
      when 1 then ( select 1 where ProductLine in ('TVs') )
      when 2 then ( select 1 where ProductLine in ('Handsets', 'Mobiles') )
      else ( select 1 where ProductLine in ('Books') )
      end is not NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM