2012-02-16 167 views
1

我試圖根據我的表中一列的值來更改我的WHERE子句。 我的表是: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 = 0includeNullType = 1,但改變我真的需要改變的唯一的事情,那就是:

@k4_type IN (SELECT typeID FROM server_updates_types sut WHERE sut.sucID = suc.sucID)

有沒有另一種方法呢?

回答

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)) 
) 
+0

我不能相信我沒有嘗試這樣做。非常感謝! – 2012-02-16 17:31:36

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)