这是我的触发器,它应该阻止用户进入" @" ," $"或" _"在城市。如果有两个条件,它完美地运作
ALTER TRIGGER i_validation
ON dbo.Customer
FOR INSERT, UPDATE
AS
DECLARE @i_not NVARCHAR(200)
begin
SELECT @i_not = dbo.Customer.City
FROM dbo.Customer
JOIN inserted ON dbo.Customer.CustomerID = inserted.CustomerID
IF((@i_not LIKE '%@%') OR (@i_not LIKE '%$%'))
BEGIN
THROW 50000, 'First name cannot contain: "@" ,"$" ,or "_"', 1;
END;
END
但是当我添加第三个条件时:
1Version.IF(( @i_not LIKE '%@%') OR ( @i_not LIKE '%$%') or @i_not LIKE '%_%' )
2Version. IF((( @i_not LIKE '%@%') OR ( @i_not LIKE '%$%')) OR @i_not LIKE '%_%' )
如果
,我还尝试了第二项ALTER TRIGGER i_validation
ON dbo.Customer
FOR INSERT, UPDATE
AS
DECLARE @i_not NVARCHAR(200)
BEGIN
SELECT @i_not = dbo.Customer.City
FROM dbo.Customer
JOIN inserted ON dbo.Customer.CustomerID = inserted.CustomerID
IF ((@i_not LIKE '%@%') OR (@i_not LIKE '%$%'))
BEGIN
THROW 50000, 'First name cannot contain: "@" ,"$" ,or "_"', 1;
END;
ELSE IF (@i_not LIKE '%_%')
BEGIN
THROW 50000, 'First name cannot contain: "@" ,"$" ,or "_"', 1;
END
END
但结果是,即使城市不包含@,$,_,它也会无视或无效。
如果有3个条件,还有其他方法吗?
答案 0 :(得分:6)
当您与LIKE
一起使用时,检查失败的原因是underscore is a special character。它匹配任何单个字符,就像%
匹配任何文本一样。
但为什么不使用检查约束?
ALTER TABLE Customer ADD CONSTRAINT check1 CHECK (City not like '%[@$_]%');
此处[@$_]
是与@
,$
或_
匹配的字符范围。下划线在字符范围内没有特殊含义。