概述
问题:
建立约束代码:
--建表
use StudentManager--指定
if exists (select *from sysobjects where name='tbl+student')--判断
drop table tbl_student--有就删除之后创建,没有就创建
create table tbl_student
(
id int identity (1,1),--自增变量从1开始增加每次加1,不设置主键,在后面添加
stu_number char(10)not null,--学号不许为空
stu_name varchar(20)not null,--注意特例
stu_age int,
birthday datetime,
class_id int --没有外键
)
use StudentManager--指定
if exists (select *from sysobjects where name='tbl_class')--判断
drop table tbl_class--有就删除之后创建,没有就创建
create table tbl_class
(
class_id int identity (1,1),--自增变量从1开始增加每次加1,不设置主键,在后面添加
class_name varchar(20)not null,
create_time datetime
)
--追加约束
--主键约束
--向哪个表加什么约束加在拿个列上
--添加主键约束(非空唯一)
alter table tbl_student add constraint PK_id primary key(id)
alter table tbl_class add constraint PK_class_id primary key(class_id)--要保证所有的约束不重名
--添加唯一约束(唯一就行可以为空)
alter table tbl_student add constraint UK_stu_number unique (stu_number)
--如果没有主键名字就会起名为随机码
--默认约束(默认有个值)
alter table tbl_class add constraint DF_create_time default (getdate())for create_time
--外键约束(保证两个表之间的对应关系)
alter table tbl_student add constraint FK_class_id foreign key (class_id )references tbl_class(class_id)
--建表时可以同时添加约束的操作如下:
create table tbl_student
(
id int identity (1,1)primary key,--设置主键约束
stu_number char(10)unique not null,--设置唯一约束
stu_name varchar(20)not null,
stu_age int check(stu_age>0 and stu_age<150),--设置检查约束
birthday datetime default(getdate()),--设置默认约束
class_id int references tbl_class(class_id)--设置外键约束
)
--删除约束
alter table tbl_student
drop constraint UK_stu_number
文件界面:
最后
以上就是甜美小蝴蝶为你收集整理的约束:确保数据的完整性(主键,唯一,检查,默认,非空,外键)的全部内容,希望文章能够帮你解决约束:确保数据的完整性(主键,唯一,检查,默认,非空,外键)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复