2012-02-06 70 views
1

我需要基於存儲過程中的參數值創建內部連接。我還使用了一個函數來將值從一串逗號分隔值中分離出來。我的代碼如下T SQL基於參數值的條件連接

Select * 
from view_Project as vp 
join inline_split_me(@earmark) as e on (vp.EarmarkId LIKE e.Value and @earmark IS NOT NULL) 

如果@earmark爲NULL,則我不希望這種加盟都發生,否則的話我有「%」或「119」或「119120121」字符串這個連接應該發生並確實產生適當的結果。我只是想,如果有是@earmark空它根本不會發生,我認爲我可以只使用和@earmark不爲空可以描述但它沒有返回正確的結果,這是通過註釋加盟發現輸出並運行與@earmark參數爲null的同一個sproc,從而爲我提供所有行。當我保留這個連接並傳遞null時,我得不到任何行,我一直在擺弄這個一段時間,任何幫助將不勝感激。

下面是函數:

[inline_split_me](@param nvarchar(MAX)) 
RETURNS TABLE AS 
RETURN(SELECT ltrim(rtrim(convert(nvarchar(4000), 
    substring(@param, Number, 
     charindex(N',' COLLATE SQL_Latin1_General_CP1_CI_AS, 
     @param + convert(nvarchar(MAX), N','), 
    Number) - 
Number) 
))) AS Value 
    FROM APM_Numbers 
    WHERE Number <= convert(int, len(@param)) 
    AND substring(convert(nvarchar(MAX), N',') + @param, Number, 1) = 
        N',' COLLATE SQL_Latin1_General_CP1_CI_AS) 

明白了,謝謝凱德空腸Roux等

if (@earmark = '%') 
select * 
    from view_Project as vp 
    where vp.EarmarkId like @earmark 
else 
select * 
    from view_Project as vp 
    where @earmark is null or vp.EarmarkId in (select Value from inline_split_me(@earmark)) 
+0

要清楚,如果@earmark爲空,結果應該是view_Project的所有內容?如果是這樣,除非傳遞給inline_split_me的空值產生不需要的結果,否則應該只能執行左外連接。 – 2012-02-06 19:47:20

+0

是的,如果@earmark爲null,則我想從view_Project – 2012-02-06 19:48:49

回答

3

INNER JOIN是你的問題。即使@earmark爲NULL時,LEFT JOIN將始終返回LEFT上的行,但連接條件永遠不會爲true。

Select * 
from view_Project as vp 
LEFT join inline_split_me(@earmark) as e on (vp.EarmarkId LIKE e.Value and @earmark IS NOT NULL) 

你可以用UNION鬼混製造行時加入@earmark爲NULL

Select * 
from view_Project as vp 
INNER join (
    SELECT Value, -- columns here ... 
    FROM inline_split_me(@earmark) as e 
    UNION ALL 
    SELECT DISTINCT vp.EarmarkId AS Value, -- NULL, NULL, etc. 
    FROM view_Project 
    WHERE @earmark IS NULL 
) AS e 
    ON vp.EarmarkId LIKE e.Value 

但坦率地說,我只想做一個條件邏輯:

IF @earmark IS NULL 
    Select * 
    from view_Project as vp 
ELSE 
    Select * 
    from view_Project as vp 
    INNER join inline_split_me(@earmark) as e on (vp.EarmarkId LIKE e.Value and @earmark IS NOT NULL) 

如果你可以脫離LIKE:

Select * 
from view_Project as vp 
WHERE @earmark IS NULL OR vp.EarmarkId IN (
    SELECT Value FROM inline_split_me(@earmark) 
) 
+0

所有結果嗯,我想這已經但結果是每一行不管我傳遞給存儲過程 – 2012-02-06 19:56:16

+0

@MichaelFullom你想要一個INNER JOIN時'@ earmark'不空值?在那種情況下,我會讓聯盟做出僞特權 - 我會更新我的答案。 – 2012-02-06 19:58:59

+0

是啊,我不需要參加如果@earmark爲null,在所有的情況發生,我只是想出會有辦法有聯接基於該參數值的方式爲空或不發生,但它聽起來像我需要在這兩種情況下都要明確? – 2012-02-06 20:02:20

0

...as vp join lined_split_me(@earmark) as... 應默認爲內聯聯接,這意味着如果在兩個表之間找到匹配項,則查詢僅返回行。 (通過明確地說inner join進行仔細檢查。)

如果@earmark爲空,函數調用是否返回no(零)行?如果是這樣,那麼應該沒有從查詢返回的行。

+0

...剛剛看到第二個評論。是的,左外連接是你想要的。 – 2012-02-06 19:52:32