我的搜索页面上有6个下拉列表,2个文本框和一个asp.net web表单应用程序中的按钮。单击按钮后,我需要选择过滤数据到转发器组件。当用户使用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 :(得分: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 :(得分:0)
SELECT * FROM Profiles WHERE (Sport = ISNULL(@Sport, Sport), Region = ISNULL(@Region, Region), Name LIKE ISNULL(@Name, Name),...
如果“empty”不是NULL(但是说空字符串),那么你可以选择使用CASE,就像这样
SELECT * FROM Profiles WHERE (Sport = CASE WHEN @Sport != '' THEN @Sport ELSE Sport END, ...
答案 2 :(得分:-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('&');