JustBeingHelpful
JustBeingHelpful

Reputation: 18990

T-SQL special characters to escape for LIKE operator wildcard search

SQL Server has the LIKE operator to handle wildcard searches. My customer wants to use the "*" (asterisk) character in the user interface of an application as the wildcard character. I'm just wondering if there are any standard characters that I need to worry about (that are used as special characters in SQL Server) besides the "%" (percent) character itself before performing a LIKE wilcard search in case their keyword contains a "%" and needs to find a "%" in the actual string. If so, what are they?

So please assume that [table1].[column1] will never have a "*" (asterisk) in the text string!

Here's what I have so far. Do I need to handle more situations other than the standard "%" character and the custom "*"

-- custom replacement
select REPLACE('xxx*xxx', '*', '%')

-- standard replacements
select REPLACE('xxx%xxx', '%', '[%]')
select REPLACE('xxx_xxx', '_', '[_]')  -- ???
select REPLACE('xxx[xxx', '[', '[[]')  -- ???
select REPLACE('xxx]xxx', ']', '[]]')  -- ???

Example:

SET @p = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@p, ']', '[]]'), '[', '[[]'), '_', '[_]'), '%', '[%]'), '*', '%')

SELECT 'xxxxxxxxx%xxxxxx' LIKE @p

SELECT [table1].[column1] LIKE @p

Upvotes: 8

Views: 20989

Answers (2)

John Bustos
John Bustos

Reputation: 19574

Looks good!! - Have a look here for all the information related to the LIKE clause.

Also List of special characters for SQL LIKE clause

Upvotes: 2

John Keller
John Keller

Reputation: 626

It looks like you got them all, although I think escaping ']' is unnecessary. Technically you should just need to escape the opening bracket ('[').

DECLARE @Table1 TABLE
(
   Column1 VARCHAR(32) NOT NULL PRIMARY KEY
);

INSERT @Table1(Column1)
VALUES
   ('abc%def'),
   ('abc_def'),
   ('abc[d]ef'),
   ('abc def'),
   ('abcdef');

DECLARE @p VARCHAR(32) = 'abc*]*';

DECLARE @Escaped VARCHAR(64) = REPLACE(@p, '[', '[[]');
SET @Escaped = REPLACE(@Escaped, '_', '[_]');
SET @Escaped = REPLACE(@Escaped, '%', '[%]');
SET @Escaped = REPLACE(@Escaped, '*', '%');

SELECT T.Column1
FROM @Table1 T
WHERE T.Column1 LIKE @Escaped;

Upvotes: 10

Related Questions