Using LIKE in selects

G

Guest

Hello.
I'm having trouble using the SQL LIKE keyword in the WHERE clause.
Specifically I have trouble using parameters like so (running against SQL
Server):
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Users WHERE first_name LIKE @first_name AND last_name
LIKE @last_name", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "@first_name";
param.Value = "Jo%";
cmd.Parameters.Add(param);
SqlParameter param = new SqlParameter();
param.ParameterName = "@last_name";
param.Value = "Sm%";
cmd.Parameters.Add(param);

The query doesn't return anything, but that table contains a row with Joe
Smith, which does turn up when I run the query in the Query Analyzer. I've
done w workaround to do text substitution for now, but that's not the correct
way to handle this. Any ideas? Thanks
 
J

Jeff Dillon

You might try running SQL Profiler to see exactly what syntax is being sent
to the server.

Jeff
 
J

Jeff Dillon

If this is C#, then the % character may be treated like an escape character.
Profiler would catch this

Jeff
 
G

Guest

Thank you! That solved my problem. Turned out I was getting an exception that
I missed catching. See the actual query going out was the trick.

Snorlax
 
C

Cowboy \(Gregory A. Beamer\)

The SQL ends up wrong the way you are doing it.

The correct query ends up more like:
"SELECT * form Users where First_name LIKE '%" + firstNameValue + "'"

When you do a LIKE with a literal and no wildcard, you are performing an
exact match, evne though you are using the like word.

--
Gregory A. Beamer

*************************************************
Think Outside the Box!
*************************************************
 
M

Miha Markic [MVP C#]

Hi Jeff,

Jeff Dillon said:
If this is C#, then the % character may be treated like an escape
character.

Nope. Only chars prefixed with \ are treated like special chars (when
strings are not prefixed with @)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top