SQLServer之修改CHECK约束

使用ssms数据库管理工具修改check约束

1、打开数据库,选择数据表-》右键点击-》选择设计(或者展开约束,选择约束,右键点击,选择修改,后面步骤相同)。

2、选择要修改的数据列-》右键点击-》选择check约束。

3、在check约束弹出框中-》选择要修改的约束-》输入约束表达式-》输入约束名和约束描述-》选择表设计器规则-》点击关闭。

 4、点击保存按钮(或者ctrl+s)-》刷新表查看修改结果。

使用t-sql脚本修改check约束

check约束修改规则必须首先删除现有的check约束,然后使用新定义重新创建,才能使用transact-sql修改check约束。

语法:

–修改check约束
use 数据库名
go

–如果约束存在则先删除
if exists(select * from sysobjects where name=约束名)
alter table 表名 drop constraint 约束名;
go

–添加约束
alter table 表名
–with check –该约束是否应用于现有数据,with check表示应用于现有数据,with nocheck表示不应用于现有数据
add constraint 约束名
check
not for replication –当复制代理在表中插入或更新数据时,禁用该约束。
(约束表达式);
go

–向表中添加新数据或更新表中现有数据时是否禁用该约束。check表示校验,nocheck表示不校验
–alter table 表名
–check
–constraint 表名;
–go

–添加check约束描述
execute sp_addextendedproperty n’ms_description’, n’约束描述’, n’schema’, n’dbo’, n’table’, n’表名’, n’constraint’, n’约束名’;
go

示例:

–修改check约束
use testss
go

–如果约束存在则先删除
if exists(select * from sysobjects where name=’u_check2′)
alter table test1 drop constraint u_check2;
go

–添加约束
alter table test1
–with check –该约束是否应用于现有数据,with check表示应用于现有数据,with nocheck表示不应用于现有数据
add constraint u_check2
check
not for replication –当复制代理在表中插入或更新数据时,禁用该约束。
(height>=100 and height <=200);
go

–向表中添加新数据或更新表中现有数据时是否禁用该约束。check表示校验,nocheck表示不校验
–alter table test1
–check
–constraint u_check2;
–go

–添加check约束描述
execute sp_addextendedproperty n’ms_description’, n’修改约束’, n’schema’, n’dbo’, n’table’, n’test1′, n’constraint’, n’u_check2′;
go

check约束修改优缺点

优点:

1、修改数据库check约束可以保证数据的规范性和完整性。

缺点:

1:修改约束的表设计器使用规则时,可能会引起原有数据与约束的冲突。

 

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐