或者LIKE sql查询布尔错误

时间:2013-11-17 00:01:39

标签: c# mysql asp.net sql sql-server

我正在尝试搜索员工记录,但我收到此错误消息:

An expression of non-boolean type specified in a context where a condition is expected, near 'OR'.

这是我正在使用的代码:

sConn = new SqlConnection(sStr);

daEmp2 = new SqlDataAdapter("
SELECT employee.*,
       department.Department
FROM tblEmployee employee
INNER JOIN tblDepartment department ON employee.DeptID=department.DeptID
WHERE Lname OR Fname LIKE '%" + txtName.Text + "%'
", sConn);

dsEmp2 = new DataSet();
daEmp2.Fill(dsEmp2, "tblEmployee");

我的查询有问题吗?

3 个答案:

答案 0 :(得分:4)

or连接SQL中的布尔条件 - 评估为true或false的条件。

你需要重复这个条件:

Lname LIKE '%" + txtName.Text + "%'" OR Fname LIKE '%" + txtName.Text + "%'"

答案 1 :(得分:3)

您的查询包含语法错误,因为您没有为Lname字段提供运算符和比较值

...  where Lname ??????? OR Fname LIKE ...

Lname后你应该添加一个运算符(=,LIKE ...)和一个比较值以允许评估表达式

...  where Lname LIKE 'AName' OR Fname LIKE ...

除此之外,请删除用于FName值的字符串连接并使用参数化查询

例如

 using(sConn = new SqlConnection(sStr))
 using(daEmp2 = new SqlDataAdapter("SELECT employee.*,department.Department " + 
                            "FROM tblEmployee employee inner join tblDepartment department " + 
                            "on employee.DeptID=department.DeptID " + 
                            "where Lname LIKE @last OR Fname LIKE @first", sConn))
 {
      daEmp2.SelectCommand.Parameters.AddWithValue("@last", "%" + LastNameTextBox.Text + "%");
      daEmp2.SelectCommand.Parameters.AddWithValue("@first", "%" + txtName.Text  + "%");
      dsEmp2 = new DataSet();
      daEmp2.Fill(dsEmp2, "tblEmployee");
 }

使用参数化查询避免了Sql Injection的可能性,从这个very famous comic strip

可以看出,安全问题非常容易利用

答案 2 :(得分:0)

您需要使用两次LIKE表达式:

"SELECT .....  WHERE Lname LIKE '%" + txtName.Text + "%' OR Fname LIKE '%" + txtName.Text + "%'"
相关问题