2014-01-23 55 views
0

在一個存儲過程中,我只想在一個查詢中包含AND子句,只要滿足一個特定的條件。動態AND子句

INSERT INTO #firstResults 
SELECT x, y, z FROM ep 
WHERE ep.proposedBy = @Id 
AND ep.pId IN (SELECT DISTINCT pId FROM #tempProj) 

只有當#tempProj不爲空時,'AND'子句才應該加入。
什麼是最優雅的方式來實現這個?

我在SQL服務器2008上。
由於這將重複多次proc,我希望避免分支IF語句。

回答

2

嘗試......

AND (ep.pId IN (SELECT DISTINCT pId FROM #tempProj) 
       OR (SELECT COUNT(*) FROM #tempProj) = 0)) 
1
IF EXISTS (SELECT * FROM #tempProj) 
BEGIN 
    INSERT INTO #firstResults 
    SELECT x, y, z FROM ep 
    WHERE ep.proposedBy = @Id 
    AND ep.pId IN (SELECT DISTINCT pId FROM #tempProj) 
END 
ELSE 
    BEGIN 
    INSERT INTO #firstResults 
    SELECT x, y, z FROM ep 
    WHERE ep.proposedBy = @Id 
    END 
0
IF EXISTS (SELECT TOP 1 NULL FROM #tempProj) 
BEGIN 
INSERT INTO #firstResults 
SELECT x, y, z FROM ep 
WHERE ep.proposedBy = @Id 
AND ep.pId IN (SELECT DISTINCT pId FROM #tempProj) 
END 
ELSE 
BEGIN 
INSERT INTO #firstResults 
SELECT x, y, z FROM ep 
WHERE ep.proposedBy = @Id 
END