我正在尝试根据表格的一列值更改我的WHERE子句。 我的表是:
server_updates
k1ID updID
----------- -----------
server_updates_cat
sucID updID catID selectChildren includeNullType
----------- ----------- ----------- ---------------- --------------
server_updates_types
sucID typeID
----------- -----------
这就是我正在做的事情:
DECLARE @k1_catID INT
DECLARE @k4_type INT
SET @k1_catID = 30
SET @k4_type = 1
SELECT suc.sucID, suc.updID FROM server_updates su
INNER JOIN server_updates_cat suc ON suc.updID = su.updID
WHERE
includeNullType = 0
AND suc.catID = @k1_catID
AND selectChildren = 1
AND @k4_type IN (SELECT typeID FROM server_updates_types sut WHERE sut.sucID = suc.sucID)
OR
includeNullType = 1
AND KSUC.catID = @k1_catID
AND selectChildren = 1
AND (@k4_type IN (SELECT typeID FROM server_updates_types sut WHERE sut.sucID = suc.sucID) OR @k4_type IS NULL)
我希望不必重复includeNullType = 0
或includeNullType = 1
的所有条件,但要改变我真正需要改变的唯一条件,即:
@k4_type IN (SELECT typeID FROM server_updates_types sut WHERE sut.sucID = suc.sucID)
还有另一种方法吗?
答案 0 :(得分:3)
WHERE suc.catID = @k1_catID
AND selectChildren = 1
AND (
(includeNullType = 0
AND @k4_type IN (SELECT typeID FROM server_updates_types sut WHERE sut.sucID = suc.sucID))
OR
(includeNullType = 1
AND (@k4_type IN (SELECT typeID FROM server_updates_types sut WHERE sut.sucID = suc.sucID) OR @k4_type IS NULL))
)
答案 1 :(得分:2)
您可以重新排列AND和OR。简化:
includeNull = 0 AND LONG_CONDITION
OR
includeNull = 1 AND (LONG_CONDITION OR COND2)
如果includeNull只能是0或1,那么这在逻辑上等同于
LONG_CONDITION OR (includeNull = 1 AND COND2)