M.Ali's answer represents the best practice for the solution you describe. That being said, I read your question differently(i.e What is wrong with they way you're implementing the like comparison.)
- You are not properly escaping wildcard characters.
- The expression
'AB' LIKE '%[AB]%
is true. The expression 'ZB' LIKE '%[^AB]%'
is also true, since that statement is the equivalent of 'Z' LIKE '[^AB]' OR 'A' LIKE '[^AB]'
Instead, you should use 'YZ' NOT LIKE '%[^AB]%'
which is the equivalent of 'Y' NOT LIKE '%[^AB]%' AND 'Z' NOT LIKE '%[^AB]%'
- You didn't escape the single quote or invisible characters. Take a look at the the ASCII characters. You would be better served implementing a solution like M.Ali's and adding any characters you do not wish to exclude.
The following script demonstrates the formation of a complex wildcard statement that consists of special characters.
-- Create sample data
-- Experiment testing various characters
DECLARE @temp TABLE (id INT NOT NULL, string1 varchar(10) NOT NULL)
INSERT INTO @temp
(id,string1)
SELECT 1, '12]34'
UNION
SELECT 2, '12[34'
UNION
SELECT 3, '12_34'
UNION
SELECT 4, '12%34'
UNION
SELECT 5, '12]34'
SET NOCOUNT ON
DECLARE @SQL_Wildcard_Characters VARCHAR(512),
@Count_SQL_Wildcard_Characters INT,
@Other_Special_Characters VARCHAR(255),
@Character_Position INT,
@Escape_Character CHAR(1),
@Complete_Wildcard_Expression VARCHAR(1024)
SET @Character_Position = 1
-- Note these need to be escaped:
SET @SQL_Wildcard_Characters = '[]^%_'
-- Choose an escape character.
SET @Escape_Character = '~'
-- I added the single quote (') ASCII 39 and the space ( ) ASCII 32.
-- You could also add the actual characters, but this approach may make it easier to read.
SET @Other_Special_Characters = '*|\":<>{}`\();@&$' + CHAR(39) + CHAR(32)
-- Quick loop to escape the @SQL_Wildcard_Characters
SET @Count_SQL_Wildcard_Characters = LEN(@SQL_Wildcard_Characters)
WHILE @Character_Position < 2*@Count_SQL_Wildcard_Characters
BEGIN
SET @SQL_Wildcard_Characters = STUFF(@SQL_Wildcard_Characters,@Character_Position,0,@Escape_Character)
SET @Character_Position = @Character_Position + 2
END
-- Concatenate the respective strings
SET @Complete_Wildcard_Expression = @SQL_Wildcard_Characters+@Other_Special_Characters
-- Shows how the statment works for match
SELECT ID, string1, @Complete_Wildcard_Expression AS [expression]
FROM @temp
WHERE string1 LIKE '%['+@Complete_Wildcard_Expression+']%' ESCAPE @Escape_Character
-- Show how the statement works fo non-match
SELECT ID, string1, @Complete_Wildcard_Expression AS [expression]
FROM @temp
WHERE string1 NOT LIKE '%[^'+@Complete_Wildcard_Expression+']%' ESCAPE @Escape_Character
RULE
. Deprecated for years. – Bedroll