Apollo
Apollo

Reputation: 2070

Escape single quote in LIKE SQl Query in C# code behind

I have a query that looks like this.

SELECT [ID], [First_Name], [Last_Name], FROM [Employees] WHERE First_Name LIKE 'Jo%'

But this does not work on C# code behind. How do I escape the first single quote after LIKE?

SqlDataAdapter da = new SqlDataAdapter("SELECT [ID], [First_Name], [Last_Name], FROM [Employees] WHERE First_Name  LIKE ' + @Search + '%'", cs);
da.SelectCommand.Parameters.AddWithValue("@Search",tbNameSearch.Text);

Upvotes: 1

Views: 744

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062975

Simply:

 ...LIKE @Search + '%' ";

Upvotes: 2

Vulcronos
Vulcronos

Reputation: 3456

Your statement should be:

"SELECT [ID], [First_Name], [Last_Name], FROM [Employees] WHERE First_Name  LIKE @Search"

Then you can change the value of @Search:value:

da.SelectCommand.Parameters.AddWithValue("@Search",tbNameSearch.Text + "%");

Upvotes: 2

Russell Uhl
Russell Uhl

Reputation: 4531

Try this:

"SELECT [ID], [First_Name], [Last_Name], FROM [Employees] WHERE First_Name LIKE '@Search%'"

The % might screw that up, I'm not sure. Try removing the % first, and if the query works, add it back in to see if anything breaks.

Upvotes: 0

Related Questions