Search for Literal Wildcards with SQL Server LIKE
In a LIKE pattern, % matches a sequence of characters and _ matches one character. When those symbols are part of the value you want to find, escape them so that they mean themselves. This pattern-level escaping is separate from safely passing values as SQL parameters.
Match a Literal Underscore
SELECT Label
FROM (VALUES (N'pump_a'), (N'pumpXa'), (N'valve_a')) AS v(Label)
WHERE Label LIKE N'pump!_a' ESCAPE N'!';
Only pump_a matches. The exclamation mark tells LIKE to interpret the next underscore literally. Without the escape, pumpXa would also match the pattern.
Build a Literal Contains Pattern
Escape the escape character first so later replacements do not re-escape characters you just added:
DECLARE @Literal nvarchar(100) = N'50%_[A]!';
DECLARE @Escaped nvarchar(200) =
REPLACE(
REPLACE(
REPLACE(
REPLACE(@Literal, N'!', N'!!'),
N'%', N'!%'),
N'_', N'!_'),
N'[', N'![');
DECLARE @Pattern nvarchar(202) = N'%' + @Escaped + N'%';
SELECT Label
FROM (VALUES
(N'Offer 50%_[A]! today'),
(N'Offer 500xxA today')
) AS v(Label)
WHERE Label LIKE @Pattern ESCAPE N'!';
The query returns only the first row, which contains the exact literal fragment. Escaping the opening bracket prevents it from starting a bracket wildcard expression. The variable sizes allow for worst-case doubling of the 100-character input plus the two outer wildcards.
Keep Query Safety Separate
Pass the resulting pattern through your database client's parameter mechanism. Do not concatenate it into an SQL statement. Wildcard escaping controls matching behavior, while parameters keep a value from becoming SQL syntax. An apostrophe inside a parameter needs no SQL-literal doubling.
Define what an empty or null search term means to the application. An empty literal surrounded by % matches every non-null value, which may be inappropriate for a bulk operation. Leading-wildcard searches can also require substantial scanning. Use this pattern when substring matching is the intended behavior, not as a substitute for an indexed exact-match query or full-text search.
Microsoft References
Author: Herman Schoenfeld