sql中为表加约束的sql语句收藏 --为表userinfo的loginName列加唯一约束
alter table userinfo
add constraint UQ_loginName unique(loginName)
--为表userinfo的loginName列加主键约束
alter table userinfo
add constraint PK_loginName primary key(loginName)
--为表userinfo的age列添加检查约束
alter table userinfo
add constraint CK_age check(age between 0 and 100)
--为表userinfo的address列添加默认约束
alter table userinfo
add constraint DF_address default('地址不详') for address
--为表userinfo的classId添加对应classinfo表的classId主键的外键
alter table userinfo
add constraint PK_classId foreign key(classId) references classinfo(classId)
--创建聚集索引
create clustered index Idx_Area_ID on Company(Area_ID)
--创建唯一聚集索引
create unique clustered index Idx_Un_Area_ID on Company(Area_ID)
--创建非聚集索引
create nonclustered index Idx_Area_ID on Company(Area_ID)
--删除约束
if exists(select * from sys.default_constraints where name='DF_address' and parent_object_id=object_id('userinfo'))
begin
alter table userinfo drop constraint DF_address
end