user1667459 user1667459 - 4 years ago 145
SQL Question

How to use the LIKE operator in a C# Command?

I need to insert a string into an Sql Command

search.CommandText = "SELECT * FROM Contacts WHERE Name like ' + @person + % + '";

What it the right way of using
in a command?

Answer Source

Should be:

SELECT * FROM Contacts WHERE Name like @person + '%'

@person is a parameter - you don't need single quotes around it. You only need to concatenate it with %, which should have quotes.

Keep in mind:

  • You could have kept it "SELECT * FROM Contacts WHERE Name like @person", and have the parameter value contain % (concatenate in C# is simpler to understand).
  • You may also want to escape other wildcard characters already in the string: %, _, [ and ].
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download