nmd*_*mdr 65 c# t-sql sql-server ado.net sql-like
我有以下代码:
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);
...
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,我也试过这个:
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 + "%'");
...
}
Run Code Online (Sandbox Code Playgroud)
但这不行.出了什么问题?有什么建议?
Mar*_*ell 128
你想要的是:
tblCustomerInfo.Info LIKE '%' + @SEARCH + '%'
Run Code Online (Sandbox Code Playgroud)
(或编辑参数值以包含%在第一位).
否则,您要么(第一个样本)搜索文字 "@SEARCH"(不是arg-value),要么在查询中嵌入一些额外的引号(第二个样本).
在某些方面,使用TSQL可能更容易LIKE @SEARCH
,并在调用者处理它:
command.Parameters.AddWithValue("@SEARCH","%" + searchString + "%");
Run Code Online (Sandbox Code Playgroud)
这两种方法都应该有效.
小智 8
而不是使用:
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%');";
Run Code Online (Sandbox Code Playgroud)
使用此代码:
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 + '%');";
Run Code Online (Sandbox Code Playgroud)
稍微注意一下Add和AddWithValue方法之间的细微差别。当我使用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
Run Code Online (Sandbox Code Playgroud)
当我将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!!!
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
60025 次 |
最近记录: |