我正在尝试编写一个类似下面的SQL查询
select [ProductId], [Product]
from Products p
where p.ProductType = case
when @condition1 then 'p'
when @condition2 then 'p','c'
else p.ProductType
end
我怎样才能做到这一点?
- 当@ccondition1为true时,我希望得到productType='p'的产品
- 当@ccondition2为true时,我想得到productType为('p','c'(的产品
- 当两个条件都为假时,则获取所有产品
您的逻辑可以在不使用case
:的情况下表达
select [ProductId], [Product]
from Products p
where (@conditionn1 and p.ProductType = 'p') or
(@conditionn2 and p.ProductType in ('p', 'c')) or
( (not @conditionn1) and (not @conditionn2) )
欢迎!
不确定我是否理解你的问题,但这是我将如何重写:
SELECT
ProductId,
Product,
CASE
WHEN p.ProductType = "CONDITION1" THEN 'p'
WHEN p.ProductType = "CONDITION2" THEN 'c'
ELSE 'ERROR'
END
FROM
Products p
不能像这样传递多个值,因为p.ProductType
可以用标量值设置;相反,你将不得不重复相同的条件,如
where p.ProductType = case
when @conditionn1 then 'p'
when @conditionn2 then 'p'
when @conditionn2 then 'c'
else p.ProductType
end