Use of SqlParameter in SQL LIKE clause not working

前端 未结 4 1185
青春惊慌失措
青春惊慌失措 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: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!!!
    

提交回复
热议问题