2

谁能知道我是否可以根据现有值在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>

我需要始终从此查询中获取数据,而不是在条件为假时获取空值。我怎么能在 SQL Server 2008 中这样做???

4

3 回答 3

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)
于 2013-02-11T19:33:23.217 回答
0
....
where tbl.idProduct = 1 
  and (CASE WHEN idProductType is not null and tbl.idProductType = SOMEVALUE Then <something> END) = <something>
/
于 2013-02-11T19:35:05.467 回答
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)
于 2013-02-11T19:33:09.650 回答