SQL QUERY格式校正

时间:2012-04-21 17:29:15

标签: c# sql asp.net-mvc

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

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 + "'";              
        }          
    }

3 个答案:

答案 0 :(得分:3)

我想你想做点什么

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

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

答案 1 :(得分: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())) + ")";
}

答案 2 :(得分: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').