2013-06-13 128 views
0

需要編寫一個過程來檢索數據,如果用戶沒有輸入值,某些選擇標準未被採納到過程中。我過濾:存儲過程過濾

WHERE @ts = [ts] or @username = [username] 
or @ip = [ip] or @my_category = [my_category] 
or @my_name = [my_name] or @nm1_name = [nm1_name] 
or @param = [param] or @short_descr = [short_descr] 

當我調用存儲過程,並通過其中的一個參數時過濾的作品,當我寫了一些,只有一個過濾工作(因爲我有我的邏輯「或」)。取而代之的是'和'不必要的不​​必要的必須通過所有的參數,我只需要傳輸我想過濾掉的那些參數。請幫我解決這個問題

+0

林不知道你想做什麼。你的意思是你想根據傳入的參數來做不同的過濾器嗎? –

回答

3

當你不使用相關的過濾器時,你將參數設置爲NULL,對嗎?在這種情況下

WHERE isnull(@ts, [ts]) = [ts] 
and isnull(@username, [username]) = [username] 
and isnull(@ip, [ip]) = [ip] 
and isnull(@my_category, [my_category]) = [my_category] 
and isnull(@my_name, [my_name]) = [my_name] 
and isnull(@nm1_name, [nm1_name]) = [nm1_name] 
and isnull(@param, [param]) = [param] 
and isnull(@short_descr, [short_descr]) = [short_descr] 
option (recompile) 

我提倡用選項(重新編譯)

編輯:

所以,你可以使用這樣的查詢

與 '',而不是NULL

WHERE @ts in ('', [ts]) 
and @username in ('', [username]) 
and @ip in ('', [ip]) 
and @my_category in ('', [my_category]) 
and @my_name in ('', [my_name]) 
and @nm1_name in ('', [nm1_name]) 
and @param in ('', [param]) 
and @short_descr in ('', [short_descr]) 

(不是使用或每一次更具可讀性和它不需要重新編譯*)

(*)作爲參數不會反正嗅

+0

爲了標記這一點,我建議@GeoVIP看一看http://www.sommarskog.se/dyn-search-2008.html中的各種方法,並且寫得很好。 – Meff

+0

@Serge,謝謝你的回答,但是當我像你的代碼一樣過濾它沒有工作。我執行如下程序:exec myProc'','Tom','','Tom','','','','' – GeoVIP

+0

嗯,你總是可以使用NULLIF。 WHERE isnull(nullfi(@ts,''),[ts])= [ts]。 – Serge

4
WHERE (@ts IS NULL OR [ts] = @ts) 
and (@username IS NULL OR [username] = @username) 
and (@ip IS NULL OR [ip] = @ip) 
and (@my_category IS NULL OR [my_category] = @my_category) 
and (@my_name IS NULL OR [my_name] = @my_name) 
and (@nm1_name IS NULL OR [nm1_name] = @nm1_name) 
and (@param IS NULL OR [param] = @param) 
and (@short_descr IS NULL OR [short_descr] = @short_descr) 

編輯:

我在其他答案的評論中,您看到的是傳遞空白字符串而不是NULL。在這種情況下,你需要處理它們(或除此之外)爲空

WHERE (@ts IS NULL OR @ts = '' OR [ts] = @ts) 
and (@username IS NULL OR @username = '' OR [username] = @username) 
and (@ip IS NULL OR @ip = '' OR [ip] = @ip) 
and (@my_category IS NULL OR @my_category = '' OR [my_category] = @my_category) 
and (@my_name IS NULL OR @my_name = '' OR [my_name] = @my_name) 
and (@nm1_name IS NULL OR @nm1_name = '' OR [nm1_name] = @nm1_name) 
and (@param IS NULL OR @param = '' OR [param] = @param) 
and (@short_descr IS NULL OR @short_descr = '' OR [short_descr] = @short_descr) 
+0

我有一個錯誤在一個上下文中指定的非布爾類型的表達式, 」。 – GeoVIP

+0

有一個錯字,一個'IS NULL'丟失了'@ ip' - 修正了 –

+0

非常感謝您的幫助。 IT WORKS – GeoVIP