0

我在我的婚姻学院项目中进行了高级搜索。结果我有以下查询:

select * 
from tbl_FreeUserProfile 
where Gender='Male' and Age>= '18' 
  and Age<= '40'    and heightf<='182' 
  and heightf>='152' and MaritalStatus='Never Married' 
  and MotherTongue = 'xyz' or 'Gujarati' or 'Urdu' or 'Hindi'"

但是当我执行查询时,它显示以下错误:

在预期条件的上下文中指定的非布尔类型的表达式,靠近“或”

谁能告诉我sql查询的格式有什么问题?

我的编码是这样的

protected void ImageButton11_Click(object sender, ImageClickEventArgs e)
  {

  string sql = "select * from tbl_FreeUserProfile where Gender='" + RadioButtonList2.SelectedItem.Text + "' and Age>= '" + DropDownList25.SelectedItem.Text + "' and Age<= '" + DropDownList26.SelectedItem.Text + "' and heightf<='" + TextBox23.Text + "' and heightf>='" + TextBox22.Text + "' and MaritalStatus='" + DropDownList35.SelectedItem.Text + "'";

  if (ListBox2.Items.Count >= 0)
    {
        sql = sql + " and MotherTongue = 'xyz'";

        for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
        {                
              string mt = ListBox2.Items[i].ToString();
              sql = sql + " or '" + mt + "'";              
        }          
    }
4

3 回答 3

3

我想你想做类似的事情

and MotherTongue IN ('xyz', 'Gujarati', 'Urdu', 'Hindi')

如果要使用or,每次都必须指定字段名称。

于 2012-04-21T17:30:55.700 回答
2

你可以这样做,使用

AND (MotherTongue = 'xyz' OR MotherTongue = 'abc' ...)

将您的代码更改为

if (ListBox2.Items.Count >= 0)
{
    sql = sql + " and ( MotherTongue = 'xyz'";

    for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
    {                
          string mt = ListBox2.Items[i].ToString();
          sql = sql + " or MotherTongue = '" + mt + "'";              
    }

    sql = sql + ")"
}

或者

AND MotherTongue IN ('xyz', 'abc', ...)

将您的代码更改为

if (ListBox2.Items.Count >= 0)
{
    sql = sql + " and MotherTongue IN (" + 
          string.Join(",", ListBox2.Items[i].Select(i => i.ToString())) + ")";
}
于 2012-04-21T17:55:02.750 回答
0

当前正在执行的查询以:

and MotherTongue = 'xyz' or 'Gujarati' or 'Urdu'... so on. 

实际查询应该是:

and MotherTongue = 'xyz' or MotherTongue =  'Gujarati' or MotherTongue = 'Urdu'

查询多种语言的最佳方法是 C.Evenhuis 提到的,即使用:

and MotherTongue IN ('xyz', 'Gujarati', 'Urdu', 'Hindi').
于 2012-04-21T17:55:28.083 回答