sql server之T-SQL语句创建约束+更改数据类型

接着上一篇QA!这里主要讲表已创建好后增加约束!这里会以实列(创建两个表的形式来讲述如何增加)不再详讲每个约束的作用。

作用:https://blog.csdn.net/qq_39657909/article/details/80550781

一、创建两个表

1.创建个人基本信息表

create table peo_info
(
id int not null,
name varchar(20) not null,
age int not null,
cool varchar not null
)
2.创建联系方式表
create table peo_cont
(
id int not null,
phone int not null,
email varchar(50) not null,
infoid int not null
)
二、T-SQL
1.为peo_info增加主键

alter table peo_info

add constraint pk_PInfo primary key(id)

注:alter table [表名] add constraint [约束名] primary key(列名)

2.为peo_info增加唯一约束

alter table peo_info

add constraint uq_PInfoName unique(name)

注:alter table [表名] add constraint [约束名] unique(列名)

3.为peo_info增加默认值约束

alter table peo_info

add constraint df_PInfoCool default('yes') for cool

注:alter table [表名] add constraint [约束名] default(默认值) for 列名

4.为peo_info增加检查约束

alter table peo_info

add constraint ck_PInfoAge check(age > 18)

注:alter table [表名] add constraint [约束名] check(检查内容)

5.为peo_con表添加外键约束

    ①.先为关联表设置主键(在以上设置过所以就不在设值主键了)

    ②.为peo_con表中的infoid字段添加外键

alter table peo_cont

add constraint fk_PCont_infoid_PInfoid foreign key(infoid) references peo_info(id)

注:alter table [表名] add constraint [约束名] foreign key(外键表列名) references [主键表名](主键表关联列名)


QAQ补:

删除约束:alter table [表名] drop constraint [约束名]

添加多个约束:

alter table [表名] add

    constraint [约束名] primary key(列名),

    constraint [约束名] unique(列名),

    constraint [约束名] default(默认值) for 列名,

    constraint [约束名] check(检查内容),

    constraint [约束名] foreign key(外键表列名) references [主键表名](主键表关联列名)

删除多个约束:

    alter table [表名] drop constraint [约束名1] , [约束名2] , [约束名3]

更改列的数据类型:

    alter table [表名] alter column [列名] int



版权声明:本博客为记录本人自学感悟,内容大多从网上学习与整理所得,若侵权请告知!

https://mp.csdn.net/postedit/80365677


猜你喜欢

转载自blog.csdn.net/qq_39657909/article/details/80554358