您的位置:首页 > 数据库

Sql中用到的与表中的约束相关的操作

2011-04-06 09:50 302 查看
在SQL数据库中与表约束相关的操作

--查询表中所有的约束

exec sp_helpconstraint @objname=xt_hetong

go

添加主键约束

alter table 表名

add constraint 约束名 primary key (主键)

---添加唯一约束

alter table 表名

add constraint 约束名 unique (字段)

---添加默认约束

alter table 表名

add constraint 约束名 default ('默认内容') for 字段

--添加检查check约束,要求字段只能在1到100之间

alter table 表名

add constraint 约束名 check (字段 between 1 and 100 )

---添加外键约束(主表stuInfo和从表stuMarks建立关系,关联字段为stuNo)

alter table 从表

add constraint 约束名

foreign key(关联字段) references 主表(关联字段)

GO

--禁止所有表约束的SQL

select 'alter table '+name+' nocheck constraint all' from sysobjects where type='U'

--删除所有表数据的SQL

select 'TRUNCATE TABLE '+name from sysobjects where type='U'

--恢复所有表约束的SQL

select 'alter table '+name+' check constraint all' from sysobjects where type='U'

--删除某字段的约束

declare @name varchar(100)

--DF为约束名称前缀

select @name=b.name from syscolumns a,sysobjects b where a.id=object_id('表名') and b.id=a.cdefault and a.name='字段名' and b.name like 'DF%'

--删除约束

alter table 表明 drop constraint 约束名
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: