Use of SqlParameter in SQL LIKE clause not working

前端 未结 4 1171
青春惊慌失措
青春惊慌失措 2020-11-27 14:53

I have the following code:

const string Sql = 
    @\"select distinct [name] 
      from tblCustomers 
      left outer join tblCustomerInfo on tblCustomers.         


        
相关标签:
4条回答
  • 2020-11-27 15:17

    Instead of using:

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

    Use this code:

    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 + '%');";
    
    0 讨论(0)
  • 2020-11-27 15:18

    Just a little careful with a slight difference between Add and AddWithValue methods. I had the problem below, when I used the Add method and put the wrong SqlType parameter.

    • nchar and nvarchar can store Unicode characters.
    • char and varchar cannot store Unicode characters.

    For example:

    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
    

    When I changed the SqlType to NVarChar, the two methods worked fine to me.

    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!!!
    
    0 讨论(0)
  • 2020-11-27 15:27

    What you want is:

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

    (or edit the parameter value to include the % in the first place).

    Otherwise, you are either (first sample) searching for the literal "@SEARCH" (not the arg-value), or you are embedding some extra quotes into the query (second sample).

    In some ways, it might be easier to have the TSQL just use LIKE @SEARCH, and handle it at the caller:

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

    Either approach should work.

    0 讨论(0)
  • 2020-11-27 15:33

    You could do LIKE @SEARCH and in your C# code, do

    searchString = "%" + searchString + "%"
    
    0 讨论(0)
提交回复
热议问题