SQL Like Clause에서 작동하지 않는 SQLPARAMETER 사용이 작동하지 않습니다
-
21-08-2019 - |
문제
다음 코드가 있습니다.
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 + "%'");
...
}
그러나 이것은 또한 작동하지 않습니다. 무엇이 잘못되고 있습니까? 제안이 있습니까?
해결책
당신이 원하는 것은 :
tblCustomerInfo.Info LIKE '%' + @SEARCH + '%'
(또는 처음에 %를 포함하도록 매개 변수 값을 편집).
그렇지 않으면, 당신은 (첫 번째 샘플) 검색입니다. 정확한 "@search"(Arg-value가 아님) 또는 쿼리 (두 번째 샘플)에 추가 인용문을 포함시킵니다.
어떤면에서는 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 + '%');";
약간의 차이로 약간 조심합니다 추가하다 그리고 AddWithValue 행동 양식. 내가 사용했을 때 나는 아래에 문제가 있었다. 추가하다 방법과 잘못된 것 sqltype 매개 변수.
nchar
그리고nvarchar
저장할 수 있습니다 유니 코드 캐릭터.char
그리고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!!!
당신은 할 수 있습니다 LIKE @SEARCH
그리고 당신의 c# 코드에서
searchString = "%" + searchString + "%"
제휴하지 않습니다 StackOverflow