[英]Sql Server WHERE IN with CASE
我們如何在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)
您無法做到這一點-您需要將其拆分為幾項檢查:
WHERE (ProductLine = 'TVs' AND @ProductType = 1)
OR (ProductLine IN ('Handsets', 'Mobiles') AND @ProductType = 2)
OR (ProductLine = 'Books' AND @ProductType NOT IN (1, 2))
您可以采用兩種方法。 我的第一個選擇是使用子查詢或通用表表達式來反轉邏輯並返回產品類型,然后匹配產品類型。 第二個是使用“ 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
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
是一個返回值的表達式。 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.