0

我将如何创建一个可以充当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 具有值,但不包括所有其他下拉列表。

我该怎么做呢?

4

3 回答 3

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.

这样,如果没有选择任何值,那么 where 子句的那部分将始终为真。

于 2013-05-17T15:02:21.160 回答
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);
于 2013-05-17T15:12:51.310 回答
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";
于 2013-05-17T15:26:21.627 回答