我想创建一个规则来限制要输入到列中的特殊字符。 我尝试了以下内容。但它没有用。
CREATE RULE rule_spchar
AS
@make LIKE '%[^[^*|\":<>[]{}`\( );@&$]+$]%'
我不知道我在这里做错了什么。任何帮助将不胜感激。
答案 0 :(得分:9)
您可以在此列上创建Check Constraint
,并且只允许Numbers
和Alphabets
插入此列,请参阅以下内容:
ALTER TABLE Table_Name
ADD CONSTRAINT ck_No_Special_Characters
CHECK (Column_Name NOT LIKE '%[^A-Z0-9]%')
ALTER TABLE Table_Name
ADD CONSTRAINT ck_Only_Numbers
CHECK (Column_Name NOT LIKE '%[^0-9]%')
ALTER TABLE Table_Name
ADD CONSTRAINT ck_Only_Alphabets
CHECK (Column_Name NOT LIKE '%[^A-Z]%')
答案 1 :(得分:1)
记住Microsoft对您正在使用或打算使用的功能的计划非常重要。 CREATE RULE
是一项不推荐使用的功能,不会长久存在。请考虑使用CHECK CONSTRAINT
。
此外,由于角色排除类实际上并不像RegEx那样运行,因此如果不对[]
进行多次调用,尝试排除方括号LIKE
是不可能的。因此,对重音不敏感的整理进行整理并使用包含字母数字的过滤器将更加成功。非拉丁字母表需要做更多的工作。
M.Ali的NOT LIKE '%[^A-Z0-9 ]%'
应该很好。
答案 2 :(得分:0)
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]%'
以下脚本演示了由特殊字符组成的复杂通配符语句的形成。
-- 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