2014-01-16 189 views
0

我有6個下拉列表,2個文本框和一個按鈕在我的asp.net網頁表單應用程序的搜索頁面。點擊按鈕後,我需要將過濾的數據選擇到中繼器組件。我可以在用戶使用SQL Select Command在所有下拉列表中選擇一些值時執行此操作。使用下拉列表篩選從數據庫中選擇

SELECT * FROM Profiles WHERE (Sport = @Sport, Region = @Region, Name LIKE @Name,...) 

但是,當用戶留下了一些下拉列表或文本框爲空SQL命令不顯示任何內容。有誰可以幫助我,如何解決這個問題?

編輯: 我修改了查詢,但它仍然不起作用。

SELECT Profiles.ProfileId,Profiles.ProPicUrl, Profiles.Name, Profiles.Specialization, UsersSports.Rating " + _ 
          "FROM Profiles " + _ 
           "JOIN UsersSports ON Profiles.ProfileId = UsersSports.ProfileId " + _ 
           "WHERE (UsersSports.SportId = CASE WHEN @SportId != '' THEN @Sport ELSE UsersSports.SportId END) AND (Region = CASE WHEN @Region != '' THEN @Region ELSE Region END) AND (Specialization = CASE WHEN @Specialization != '' THEN @Specialization ELSE Specialization END)" + _ 
             "AND (Sex = CASE WHEN @Sex != '' THEN @Sex ELSE Sex END) AND ((@AgeFrom IS NOT NULL AND @AgeTo IS NOT NULL AND Age BETWEEN @AgeFrom AND @AgeTo) OR (@AgeFrom IS NULL AND @AgeTo IS NULL AND Age)) " + _ 
             "AND ((@PractiseFrom IS NOT NULL AND @PractiseTo IS NOT NULL AND Practise BETWEEN @PractiseFrom AND @PractiseTo) OR (@PractiseFrom IS NULL AND @PractiseTo IS NULL AND Practise))" + _ 
             "AND ((@Name IS NOT NULL AND Name LIKE '%@Name%') OR (@Name IS NULL AND Name)) AND ((@City IS NOT NULL AND City LIKE '%@City%') OR (@City IS NULL AND City))" + _ 
           "ORDER BY UsersSports.Rating ASC 
+0

另外'LIKE'應該像''%@ Name%''一樣使用,否則它就像'='一樣工作。 – user2989408

回答

0
SELECT * FROM Profiles WHERE (Sport = ISNULL(@Sport, Sport), Region = ISNULL(@Region, Region), Name LIKE ISNULL(@Name, Name),... 

如果「空」不爲空(但說空字符串),那麼你必須用例的選項,這樣

SELECT * FROM Profiles WHERE (Sport = CASE WHEN @Sport != '' THEN @Sport ELSE Sport END, ... 
+0

在WHERE子句中使用'ISNULL()'函數是不好的做法。 –

2

它應該是如下 - 只是確保當沒有選擇下拉列表中,該參數設置爲NULL

SELECT * FROM Profiles 
WHERE (@Sport IS NULL OR Sport = @Sport) 
    AND (@Region IS NULL OR Region = @Region) 
    AND (@Name IS NULL OR Name LIKE @Name) 
-1

嘗試類似如下:

String query = "SELECT * FROM Profiles WHERE"; 

if(ddlSports.SelectedIndex>0) 
    query +=" Sports='"+ddlSports.SelectedValue+"' &"; 

if(!String.IsNullOrEmpty(txtRegion.Text)) 
    query +=" Region='"+txtRegion.Text+"' &" 
.. 
.. 
.. 
and so on 

query = query.TrimEnd('&'); 
+0

你好SQL注入 – Fredou

+0

沒有必要使用動態SQL - 這是可能的正則SQL。 –

相關問題