T-SQL使用约束

勤奋不是嘴上说说而已,而是实际的行动,在勤奋的苦度中持之以恒,永不退却。业精于勤,荒于嬉;行成于思,毁于随。在人生的仕途上,我们毫不迟疑地选择勤奋,她是几乎于世界上一切成就的催产婆。只要我们拥着勤奋去思考,拥着勤奋的手去耕耘,用抱勤奋的心去对待工作,浪迹红尘而坚韧不拔,那么,我们的生命就会绽放火花,让人生的时光更加的闪亮而精彩。

导读:本篇文章讲解 T-SQL使用约束,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

约束是在表中定义的用于维护数据库完整性的一些规则

常用的约束类型如下:

约束类型 备注
主键约束:(Primary Key constraint) 要求主键列唯一,并且不允许为空
唯一约束:(Unique Constraint) 要求该列唯一,允许为空,但只能出现一个空值
检查约束:(Check Constraint) 某列取值范围限制、格式限制等。如有关年龄的限制
默认约束:(Default Constraint) 某列的默认值,如我们的男性学员比较多,性别默认为男
外键约束:(Foreign Key Constraint) 用于在两表之间建立关系,需要指定引用主表的哪一列

添加删除约束

--添加约束
alter table 表名   
add constraint  约束名 约束类型 具体的约束类型  
--删除约束
alter table 表名   
drop constraint  约束名  

--在创建表的时候同时添加约束
create table stuInfo   
(
stuName varchar(20) not null primary key(stuName)--主键约束
stuID int not null unique(stuID)--唯一约束
stuAddress varchar(20) not null default('地址不详')--默认约束
stuAge int not null check(stuAge between 15 and 40) --检查约束
)  

1.增加主键约束

--为course添加主键约束
alter table course
add
constraint pk_course primary key(couno, couname)

2.增加外键约束

--为course添加外键约束
alter table course
add
constraint fk_course foreign key(stuno)
references studentinfo(stuno)

3.增加check约束

--为course中的分数添加检查约束
alter table course
add
constraint ck_course_1
check(coucredit > 1)
--为course中的room添加检查约束
alter table course
add
constraint ck_course_2
check(couroom like '1%')

4.删除约束

alter table course drop ck_course_1

5.设置主键自增长列

1.新建一数据表,里面有字段id,将id设为为主键
create table tb(id int,constraint pkid primary key (id))
create table tb(id int primary key )

2.新建一数据表,里面有字段id,将id设为主键且自动编号
create table tb(id int identity(1,1),constraint pkid primary key (id))
create table tb(id int identity(1,1) primary key )


3.已经建好一数据表,里面有字段id,将id设为主键
alter table tb alter column id int not null 
alter table tb add constraint pkid primary key (id)

4.删除主键

Declare @Pk varChar(100);
Select @Pk=Name from sysobjects where Parent_Obj=OBJECT_ID('tb') and xtype='PK';
if @Pk is not null
exec('Alter table tb Drop '+ @Pk)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/140786.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!