如何在SQL Server中对两个值进行搜索查询

我制作了一个C#表单,在一个表中搜索两个值。 我的表称为具有字符串ID和字符串cust_name customers

我需要创建一个查找文本框的搜索查询文本可以在IDcust_name ,所以我在textChanged发送此方法时进行了此SQL查询

 search(txt_search.Text); SqlDataAdapter searchAdapter; private void search(string id) { searchAdapter = new SqlDataAdapter(@"Select * from Customers where cust_ID like '%' '" + id + "' '%' or cust_name like '%' '" + id + "' '%'", User.connection); } 

请帮我把它弄好..

像往常一样,使用参数化查询。 您的错误是在进行查询的字符串部分的串联中。 并且常见的情况是某些东西不是应该的。 在您的特定情况下,有一些空格会弄乱语法。 无论如何参数允许更清晰的查询文本,避免Sql注入和解析错误。

 private void search(string id) { string cmdText = @"Select * from Customers where cust_ID like @id or cust_name like @id"; searchAdapter = new SqlDataAdapter(cmdText, User.connection); searchAdapter.SelectCommand.Parameters.Add("@id", SqlDbType.NVarChar).Value = "%" + id + "%"; ... remainder of the code that uses the searchAdapter.... }