What characters need to be escaped in a Sql Server LIKE query

Starnuto di topo picture Starnuto di topo · Nov 22, 2017 · Viewed 10k times · Source

The LIKE operator in a SQL server query can be very useful to match custom patterns. However sometimes the need raises to escape some characters or substrings from the pattern, such as ampersands '%', underscores '_', square brackets '[' and ']', etc.

Indeed I'm using parametrized queries but it does not solve LIKE case because for example searching for _ would mean "any character".

What is the set of characters that must be considered while escaping such patterns? Can a C# function be provided to perform a safe escape?

Answer

spodger picture spodger · Nov 22, 2017

%, _, [, ], and ^ need to be escaped, and you will need to choose a suitable escape character, i.e. one that you aren't using elsewhere in your LIKE pattern.

Full description here LIKE (Transact-SQL)

I'm sure you could write a function in C# to do that.