Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of SqlParameter in SQL LIKE clause not working

I have the following 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%');";  using (var command = new SqlCommand(Sql, Connection)) {            command.Parameters.AddWithValue("@SEARCH", searchString);     ... } 

This does not work, I tried this as well:

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

but this does not work as well. What is going wrong? Any suggestions?

like image 824
coder_bro Avatar asked Mar 20 '09 05:03

coder_bro


People also ask

What does like %% mean in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Does not like work in SQL?

The NOT LIKE operator in SQL is used on a column which is of type varchar . Usually, it is used with % which is used to represent any string value, including the null character \0 . The string we pass on to this operator is not case-sensitive.

What is the use of '@' in SQL?

The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables.

Can we use like with in clause in SQL?

the LIKE operation is not permitted to be used with IN.


1 Answers

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.

like image 56
Marc Gravell Avatar answered Sep 18 '22 17:09

Marc Gravell