Development Tip

SQL LIKE 절에서 SqlParameter 사용이 작동하지 않음

yourdevel 2020. 11. 17. 21:11
반응형

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

AddAddWithValue 메서드 의 약간의 차이에 약간주의 하십시오 . Add 메서드를 사용 하고 잘못된 SqlType 매개 변수를 입력 했을 때 아래 문제가 발생했습니다 .

  • ncharnvarchar저장할 수있는 유니 코드 문자를.
  • 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

SqlTypeNVarChar로 변경했을 때 두 가지 방법이 잘 작동했습니다.

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

반응형