반응형
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 + "%'");
...
}
그러나 이것은 잘 작동하지 않습니다. 무엇이 잘못 되었나요? 어떤 제안?
당신이 원하는 것은 :
tblCustomerInfo.Info LIKE '%' + @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 + '%');";
Add 와 AddWithValue 메서드 의 약간의 차이에 약간주의 하십시오 . Add 메서드를 사용 하고 잘못된 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 + "%"
참고 URL : https://stackoverflow.com/questions/665129/use-of-sqlparameter-in-sql-like-clause-not-working
반응형
'Development Tip' 카테고리의 다른 글
힘내 : "이전 커밋없이 '스쿼시'할 수 없습니다"오류를 rebase하는 동안 (0) | 2020.11.17 |
---|---|
SQL Server에서 VARCHAR / CHAR 대신 NVARCHAR / NCHAR을 언제 사용해야합니까? (0) | 2020.11.17 |
MVC 대 3 계층 아키텍처? (0) | 2020.11.17 |
활성 메뉴 항목-asp.net mvc3 마스터 페이지 (0) | 2020.11.17 |
Google C ++ 스타일 가이드의 예외 없음 규칙; (0) | 2020.11.17 |