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?
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.
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.
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.
the LIKE operation is not permitted to be used with IN.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With