Using "Like" operator in parameterized queries

As you know parameterized queries has two benefit against regular queries .

First for preventing of some SQL injection attacks and second take advantages of  query plan caching.

One simple example is like this.

string command = "Select FirstName from UsersTable where Age = @Age";

SqlCommand cmd = new SqlCommand(command);

cmd.Parameters.AddWithValue("@Age", textBox1.Text);

But if you want to use "Like" operator in query, scenario is a bit different.

In this post I introduce two way for doing that.

1 . using "Like" operator with plus sign in query :

string command = "Select FirstName from UsersTable where FirstName Like '%'+ @FirstName + '%' ";

SqlCommand cmd = new SqlCommand(command);

cmd.Parameters.AddWithValue("@FirstName", textBox1.Text);

2. using percentage sign when parameter assignments :

string command = "Select FirstName from UsersTable where FirstName Like @FirstName";

SqlCommand cmd = new SqlCommand(command);

cmd.Parameters.AddWithValue("@FirstName", string.Format("%{0}%", textBox1.Text));

Have a good time!

Published Friday, December 19, 2008 11:31 AM by mlife

Comments

# Using "Like" operator in parameterized queries - Morteza Sahragard

Pingback from  Using "Like" operator in parameterized queries - Morteza Sahragard

# re: Using "Like" operator in parameterized queries

Friday, December 19, 2008 3:10 PM by AndrewSeven

Doesn't #1 have a potential Sql injection problem?

------------------------------------------------------------------------

@ AndrewSeven

No , that is safe, you can test it.

# re: Using "Like" operator in parameterized queries

Monday, July 13, 2009 3:05 PM by Alex

Thanks a million for this post; I'd been trying to debug my asp.net sql statement for a while and couldn't figure out why the sql statement wouldn't execute properly within .net.

# re: Using "Like" operator in parameterized queries

Friday, May 28, 2010 11:31 AM by DChiShaggy

Thank you very much for this post.  This will helps me with a search bar on an inventory system I am working on.

# re: Using "Like" operator in parameterized queries

Tuesday, November 16, 2010 2:10 PM by skm1837

Thank you!!! I added '%' into query but now I can add it as parameter.

# re: Using "Like" operator in parameterized queries

Sunday, April 17, 2011 6:52 AM by Kasun Wickramarathna

Thank you .It works...

I used No 1 option

on data binding controls

Leave a Comment

(required) 
(required) 
(optional)
(required)