1

我有以下约束,应该只允许插入 0 到 9 的数字,而不是任何特殊字符和字母字符。但情况并非如此,例如在使用此更新语句时:

   update MyDB.dbo.MyTable 
    set MyTestPhoneExt = '23&'  where ID = 1;

目标是确保源数据和写入 MyTable 的数据只有数字,但 MyTestPhoneExt 字段必须为VARCHAR(15) NULL。

ALTER TABLE MyDB.dbo.MyTable  WITH CHECK ADD CONSTRAINT [CHK_MyDB_MyTable _MyTestPhoneExt] 
CHECK ((MyTestPhoneExt IS NULL OR LEN(MyTestPhoneExt)>=(1) AND

LEN(MyTestPhoneExt)<=(15) AND MyTestPhoneExt LIKE '%[0-9]%' 

--OR len(MyTestPhoneExt)>=(1) AND len(MyTestPhoneExt)<=(15) 

AND NOT MyTestPhoneExt LIKE '%[a-zA-Z]%' 
AND NOT (MyTestPhoneExt=' ' OR MyTestPhoneExt='' OR MyTestPhoneExt='&' OR

MyTestPhoneExt='`' OR MyTestPhoneExt='~' OR MyTestPhoneExt='>' OR 

MyTestPhoneExt='<' OR MyTestPhoneExt='.' OR MyTestPhoneExt=',' OR 

MyTestPhoneExt=';' OR MyTestPhoneExt=':' OR MyTestPhoneExt='?' OR 

MyTestPhoneExt='_' OR MyTestPhoneExt='=' OR MyTestPhoneExt='+' OR

MyTestPhoneExt='!' OR MyTestPhoneExt='@' OR MyTestPhoneExt='#' OR

MyTestPhoneExt='%' OR MyTestPhoneExt='$' OR MyTestPhoneExt='^' OR

MyTestPhoneExt='*' OR MyTestPhoneExt=',' OR MyTestPhoneExt='}' OR

MyTestPhoneExt='{' OR MyTestPhoneExt=')' OR MyTestPhoneExt='(' OR 

MyTestPhoneExt=']' OR MyTestPhoneExt='[' OR MyTestPhoneExt='|' OR 

MyTestPhoneExt='\' OR MyTestPhoneExt='/' OR MyTestPhoneExt='-' OR MyTestPhoneExt='@')))
4

3 回答 3

2

这不是只接受数字的更简单方法吗?

patindex('%[^0-9]%', MyTestPhoneExt) = 0
于 2018-03-09T04:23:25.567 回答
2

尝试使用PATINDEX内部CHECK CONSTRAINT

CREATE TABLE Mytable
(
    MyCol NVARCHAR(50) CHECK(PATINDEX('%[^0-9]%',MyCol)=0 AND ISNUMERIC(MyCol) = 1)
)

INSERT INTO Mytable
(
    MyCol
)
VALUES(1),(2)

INSERT INTO Mytable
(
    MyCol
)
VALUES('1B'),('2A')

INSERT INTO Mytable
(
    MyCol
)
VALUES('1.0'),('2.5')


INSERT INTO Mytable
(
    MyCol
)
VALUES('1 '),('2 x')

SELECT
    *
    FROM Mytable
于 2018-03-09T04:24:12.063 回答
0

要仅允许数值,您可以使用TRY_CONVERT()带有检查约束的函数

ALTER TABLE table    
ADD CONSTRAINT CHK_MyDB_MyTable _MyTestPhoneExt 
                         CHECK(TRY_CONVERT(BIGINT, MyTestPhoneExt) IS NOT NULL)

您还可以使用系统功能ISNUMERIC()

ALTER TABLE table    
ADD CONSTRAINT CHK_MyDB_MyTable _MyTestPhoneExt 
                             CHECK(ISNUMERIC(MyTestPhoneExt)=1)
于 2018-03-09T04:15:17.333 回答