I am doing a really simple query in ASP.NET, but after I inserted the LIKE
clause it stops working.
Example:
String sql = " SELECT *
FROM Products
WHERE ID = @MYID
AND Name LIKE '%@MYNAME%' ";
SqlCommand command = new SqlCommand(sql, cn);
command.Parameters.AddWithValue("@MYID", MYID.Text);
command.Parameters.AddWithValue("@MYNAME", MYNAME.Text);
If I removed the LIKE it works. Hence I am thinking its to do with the '' quotes?
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.
There is no combination of LIKE & IN in SQL, much less in TSQL (SQL Server) or PLSQL (Oracle). Part of the reason for that is because Full Text Search (FTS) is the recommended alternative.
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters.
1 Answer. The correct answer to the question “Which of the SQL statements is correct” is option (b). SELECT Username, Password FROM Users. And all the other options are incorrect.
The original code is confusing the text of the SQL statement with the content of the parameter. Your code should actually look like this:
string sql = "SELECT *
FROM Products
WHERE ID = @MyID
AND Name LIKE @MyName";
using (SqlCommand command = new SqlCommand(sql, cn))
{
command.Parameters.AddWithValue("@MyID", MyID.Text);
command.Parameters.AddWithValue("@MyName", "%" + MyName.Text + "%");
// Etc.
}
The %
signs need to be part of the parameter value, and you don't need the single quotes at all when using binding parameters.
Just a note to say that using LIKE with an initial wildcard is almost always a very bad idea, because the query won't use any indexes on that column. In this case you can probably get away with because it looks like the filter on the ID column will limit you to one record, but generally what you need to do instead is put a full-text index on the name column and write the query like this:
... WHERE CONTAINS(name, @MyName)
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