2

我们如何在 WHERE 子句中指定 CASE 的值范围?
我的这个查询失败了

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
)

这也行不通:

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)
4

4 回答 4

6

您不能这样做 - 您需要将其拆分为多个检查:

WHERE (ProductLine = 'TVs' AND @ProductType = 1)
   OR (ProductLine IN ('Handsets', 'Mobiles') AND @ProductType = 2)
   OR (ProductLine = 'Books' AND @ProductType NOT IN (1, 2))
于 2012-05-09T01:24:49.607 回答
2
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)
于 2012-05-09T01:27:00.987 回答
1

您可以采用两种方法。我的第一个选择是使用子查询或公用表表达式来反转逻辑并返回产品类型,然后匹配产品类型。第二个是使用“sp_executesql”。

第一个选项:

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

第二种选择:

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
于 2012-05-09T07:07:50.493 回答
0

CASE是一个返回值的表达式。 IN是一个可能是查询一部分的子句。SQL Server 只勉强支持布尔数据类型。

您可以这样组合它们:

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
于 2012-05-09T03:29:40.800 回答