在SQL LIKE子句中使用SqlParameter不起作用
我有以下代码:
const string Sql = @"select distinct [name] from tblCustomers left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId where (tblCustomer.Name LIKE '%@SEARCH%' OR tblCustomerInfo.Info LIKE '%@SEARCH%');"; using (var command = new SqlCommand(Sql, Connection)) { command.Parameters.AddWithValue("@SEARCH", searchString); ... } 这不起作用,我也试过这个:
 const string Sql = @"select distinct [name] from tblCustomers left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId where (tblCustomer.Name LIKE @SEARCH OR tblCustomerInfo.Info LIKE @SEARCH );"; using (var command = new SqlCommand(Sql, Connection)) { command.Parameters.AddWithValue("@SEARCH", "'%" + searchString + "%'"); ... } 
但是这不起作用。 出了什么问题? 有什么build议么?
你想要的是:
 tblCustomerInfo.Info LIKE '%' + @SEARCH + '%' 
(或编辑参数值以在第一位包含%)。
否则,您要么search文字 “@SEARCH”(不是参数值),要么search一个额外的引号(第二个样本)。
 在某些方面,TSQL可能更容易使用LIKE @SEARCH ,并在调用者处理它: 
 command.Parameters.AddWithValue("@SEARCH","%" + searchString + "%"); 
这两种方法都应该有效。
而不是使用:
 const string Sql = @"select distinct [name] from tblCustomers left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId where (tblCustomer.Name LIKE '%@SEARCH%' OR tblCustomerInfo.Info LIKE '%@SEARCH%');"; 
使用此代码:
 const string Sql = @"select distinct [name] from tblCustomers left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId where (tblCustomer.Name LIKE '%' + @SEARCH + '%' OR tblCustomerInfo.Info LIKE '%' + @SEARCH + '%');"; 
 你可以做LIKE @SEARCH ,在你的C#代码中做 
 searchString = "%" + searchString + "%"