86

我有以下代码:

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

但这也不起作用。出了什么问题?有什么建议么?

4

4 回答 4

176

你想要的是:

tblCustomerInfo.Info LIKE '%' + @SEARCH + '%'

(或编辑参数值以首先包含 %)。

否则,您要么(第一个示例)搜索文字“@SEARCH”(而不是 arg 值),要么将一些额外的引号嵌入到查询中(第二个示例)。

LIKE @SEARCH在某些方面,让 TSQL 只使用并在调用者处处理它可能更容易:

command.Parameters.AddWithValue("@SEARCH","%" + searchString + "%");

任何一种方法都应该有效。

于 2009-03-20T06:02:02.290 回答
9

而不是使用:

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 + '%');";
于 2016-09-10T07:42:01.350 回答
6

请注意AddAddWithValue方法之间的细微差别。当我使用Add方法并输入错误的SqlType参数时,我遇到了以下问题。

  • nchar并且nvarchar可以存储Unicode字符。
  • char并且不能存储 Unicode字符。varchar

例如:

string query = " ... WHERE stLogin LIKE @LOGIN ";

SqlParameter p = new SqlParameter("@LOGIN", SqlDbType.Char, 255) 
{ 
    Value = "%" + login + "%" 
};

command.Parameters.AddWithValue(p.ParameterName, p.Value); //works fine!!!

command.Parameters.Add(p); // won't work

当我将SqlType更改为NVarChar时,这两种方法对我来说都很好。

SqlParameter p = new SqlParameter("@LOGIN", SqlDbType.NVarChar, 255) 
{ 
    Value = "%" + login + "%" 
};

command.Parameters.AddWithValue(p.ParameterName, p.Value); //worked fine!!!

command.Parameters.Add(p); //worked fine!!!
于 2019-01-31T13:00:45.087 回答
-7

你可以LIKE @SEARCH在你的 C# 代码中做

searchString = "%" + searchString + "%"
于 2009-03-20T06:18:01.800 回答