有人知道我是否可以根据现有值使用“条件”和“在where子句中”,我有这样的查询:
@declare idProduct int = 1,
@declare idProducType int = null
select
tbl.idProduct, tbl.idProductType, tbl.ProductName, tbl.ProductPrice
from MyTable tbl
where tbl.idProduct = 1
<IF idProductType is not null>
and tbl.idProductType = SOMEVALUE
<ELSE>
do nothing
<ENDIF>
我需要始终从此查询中获取数据,而不是在条件为false时获取空值。我怎么能在SQL Server 2008中这样做???
答案 0 :(得分:2)
我认为这就是你想要的:
select
tbl.idProduct, tbl.idProductType, tbl.ProductName, tbl.ProductPrice
from MyTable tbl
where tbl.idProduct = 1 and (tbl.idProductType = @idProducType or @idProducType is null)
答案 1 :(得分:0)
这应该适合你:
@declare idProduct int = 1,
@declare idProducType int = null
SELECT
tbl.idProduct, tbl.idProductType, tbl.ProductName, tbl.ProductPrice
FROM MyTable tbl
WHERE tbl.idProduct = 1
AND (CASE WHEN idProductType is not null THEN tbl.idProductType = SOMEVALUE
END)
答案 2 :(得分:0)
....
where tbl.idProduct = 1
and (CASE WHEN idProductType is not null and tbl.idProductType = SOMEVALUE Then <something> END) = <something>
/