我有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
另外'LIKE'應該像''%@ Name%''一樣使用,否則它就像'='一樣工作。 – user2989408