M.Ali 的回答代表了您描述的解决方案的最佳实践。话虽这么说,我以不同的方式阅读了您的问题(即,您执行类似比较的方式有什么问题。)
- 您没有正确转义通配符。
- 表达式
'AB' LIKE '%[AB]% 为真。表达式'ZB' LIKE '%[^AB]%' 也是正确的,因为该语句等同于'Z' LIKE '[^AB]' OR 'A' LIKE '[^AB]' 相反,您应该使用'YZ' NOT LIKE '%[^AB]%',它等同于'Y' NOT LIKE '%[^AB]%' AND 'Z' NOT LIKE '%[^AB]%'
- 您没有转义单引号或不可见字符。看看ASCII characters. 你会更好地实施像 M.Ali's 这样的解决方案并添加你希望排除的任何字符不。
以下脚本演示了由特殊字符组成的复杂通配符语句的形成。
-- 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