我如何创建一个可以充当where
子句的字符串?
目前,我这样做:
string strquery = "select * from tbl_DR_data ";
string strq2 = "where [Year 1]='" + DropDownList1.SelectedItem.Text + "'and Product='" + DropDownList2.SelectedItem.Text +
"'and Media='" + DropDownList3.SelectedItem.Text + "'and Publication='" + DropDownList4.SelectedItem.Text + "'and Genre='" + DropDownList5.SelectedItem.Text +
"'and Month='" + DropDownList6.SelectedItem.Value + "'and Section='" + DropDownList7.SelectedItem.Text + "'";
string str3 = strquery + strq2;
但问题是所有下拉列表都必须包含值。 我希望能够根据下拉列表中的值在init中创建一个where语句。因此,示例DDL1和DDL4具有值,但不包括所有其他下拉列表。
我将如何做到这一点??
答案 0 :(得分:0)
您可以将选择查询格式化为 -
select * from tbl_DR_data
where
ISNULL( [YEAR 1], 'X') = ISNULL( DropDownList1.SelectedItem.Text, 'X')
AND ISNULL( Product, 'X') = ISNULL( DropDownList2.SelectedItem.Text , 'X')
AND ... so on.
这样,如果没有选择任何值,那么wher子句的那一部分将永远为真。
答案 1 :(得分:0)
string strq2 = "where '";
if(!string.IsNullOrEmpty(DropDownList1.SelectedItem.Text))
strq2 = strq2 + "[Year 1]='" + DropDownList1.SelectedItem.Text + " and ";
if(!string.IsNullOrEmpty(DropDownList2.SelectedItem.Text))
strq2 = strq2 + "Product='" + DropDownList2.SelectedItem.Text+ " and ";
if(!string.IsNullOrEmpty(DropDownList3.SelectedItem.Text))
strq2 = strq2 + "Media='" + DropDownList3.SelectedItem.Text+ " and ";
if(!string.IsNullOrEmpty(DropDownList4.SelectedItem.Text))
strq2 = strq2 + "Publication='" + DropDownList4.SelectedItem.Text+ " and ";
if(!string.IsNullOrEmpty(DropDownList5.SelectedItem.Text))
strq2 = strq2 + "Genre='" + DropDownList5.SelectedItem.Text+ " and ";
if(!string.IsNullOrEmpty(DropDownList6.SelectedItem.Value))
strq2 = strq2 + "Month='" + DropDownList6.SelectedItem.Value+ " and ";
if(!string.IsNullOrEmpty(DropDownList7.SelectedItem.Value))
strq2 = strq2 + "Section='" + DropDownList7.SelectedItem.Value+ " and ";
strq2 = strq2.Remove(strq2.Length - 5);
答案 2 :(得分:0)
您必须学习并使用SqlParameter
对象..
string strq2 = "WHERE 1=1";
if(!string.IsNullOrEmpty(DropDownList1.SelectedItem.Text))
strq2 += " AND [Year 1]=@Year1";
if(!string.IsNullOrEmpty(DropDownList2.SelectedItem.Text))
strq2 += " AND [Product]=@Product";
if(!string.IsNullOrEmpty(DropDownList3.SelectedItem.Text))
strq2 += " AND [Media]=@Media";
if(!string.IsNullOrEmpty(DropDownList4.SelectedItem.Text))
strq2 += " AND [Publication]=@Publication";
if(!string.IsNullOrEmpty(DropDownList5.SelectedItem.Text))
strq2 += " AND [Genre]=@Genre";
if(!string.IsNullOrEmpty(DropDownList6.SelectedItem.Value))
strq2 += " AND [Month]=@Month";
if(!string.IsNullOrEmpty(DropDownList7.SelectedItem.Value))
strq2 += " AND [Section]=@Section";