sql语句为varchar(n)类型的数据设置完整性约束

img


telephone的数据类型为varchar(11),要将telephone的完整性约束设置为数字字符,怎么写sql语句

创建表后,可试试设置约束Check
Create table store (
    stno char(3) not null,
    address nvarchar(30) not null,
    telephone varchar(11),
    capacity smallint
  constraint PK_store primary key nonclustered  --设置主键
  ( stno ASC )
) --on Check_Data  --测试文件组

Alter table store with check     --设置约束关键字check
   Add constraint CK_store_stno  --约束名CK_store_stno
   Check (patindex('%[^0-9]%', telephone) = 0)  --字段规则

Alter table store check constraint CK_store_stno  --对应上一句约束名CK_store_stno

insert into store(stno,address,telephone,capacity)
values ('001','月亮阁','12345678901',999);  --测试telephone数字字符 正常插入

insert into store(stno,address,telephone,capacity)
values ('002','逍遥湾','12345678-CK',600);  --测试telephone非数字字符应有告警信息

img

telephone varchar(11) check (telephone in ('0','1','2','3','4','5','6','7','8','9'))