[英]How to provide multiple values in THEN for a where clause in SQL
我正在尝试编写如下所示的 SQL 查询
select [ProductId], [Product]
from Products p
where p.ProductType = case
when @condition1 then 'p'
when @condition2 then 'p','c'
else p.ProductType
end
我怎样才能做到这一点?
欢迎!
不确定我是否理解你的问题,但这是我重写的方式:
SELECT
ProductId,
Product,
CASE
WHEN p.ProductType = "CONDITION1" THEN 'p'
WHEN p.ProductType = "CONDITION2" THEN 'c'
ELSE 'ERROR'
END
FROM
Products p
您的逻辑可以在不使用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) )
你不能像这样传入多个值,因为p.ProductType
可以用标量值设置; 相反,您将不得不重复相同的条件,例如
where p.ProductType = case
when @conditionn1 then 'p'
when @conditionn2 then 'p'
when @conditionn2 then 'c'
else p.ProductType
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.