SQLServer创建约束

--创建数据库
create database students
on primary
(
    name=stu_data,
    filename='f:\SQL\stu_data.mdf',
    size=1,
    maxsize=10,
    filegrowth=1
)
log on
(
    name=stu_log,
    filename='f:\SQL\stu_log.ldf',
    size=1,
    maxsize=10,
    filegrowth=1
)
--删除数据库
drop database students
--使用数据库
use students
--删除表
drop table score
drop table student
drop table class
--自定义类型
Exec sp_addtype age,int ,'not null'
--定义表时第一种方法创建主键外健

create table student
(
    fCode char(10) identity(1,2) constraint PK_fCode1 primary key,
    fName varchar(15) not null constraint DF_fName default 'sss',
    fClass varchar(5) not null default '',
    fSex varchar(2)  not null default ''constraint CK_fSex check (fSex in('男 ','女')),
    fAge age
)
create table score
(
    fId char(10) constraint FK_fId foreign key (fId)references student,
    fSubject varchar(10) not null default '',
    fScore int not null default 0 constraint CK_fScore check(fScore>=0 and fScore<=100)
)
--定义表时第二种方法创建主键外键
create table class
(
    fClassId int not null,
    fTeacherName varchar(10) not null,
    fYear varchar(4)not null unique,
    constraint PK_fClassId primary key (fClassId),
    constraint FK_fClassId foreign key (fClassId) references student
    
)
--实例表
drop table A
create table A
(
    fCode int not null,
    fClassId varchar(5)not null,
    fName varchar(4)not null,
    fSex varchar(2)not null,
    
)
--添加唯一性约束
alter table A
add constraint UQ_fClassId_A unique(fClassId)
--添加主键,默认值,检查,外键约束
alter table A
add constraint  PK_fCode_A primary key(fCode)

alter table A
add constraint DF_fName_A default '' for fName

alter table A
add constraint CK_fSex_A check(fsex in('男','女'))

alter table A
add constraint FK_fCode_A foreign key(fCode) references student
--删除约束
alter table A
drop constraint DF_fName_A
--增加列
alter table A
add fAge int null
--删除列
alter table A
drop column fAge

/*注意
    1、主键表中主键列的类型和长度必须和外键表中列的类型和长度相同
    2、外键表中列的取值只能是主键表中主键列的子集*/
    
    
/*
--新增所有列数据
insert into student values('李鸿','0201','女',23)
insert into student values('John','0201','男',23)
insert into score values(1,'英语',90)
insert into class values(1,'逐月','2002')
insert into score values(2,'英语',102)
--新增数据部分列
insert into student(fName,fSex) values('桐港','男')

select * from student
select * from score
select * from class*/

转载于:https://www.cnblogs.com/zhangyongjian/p/3616897.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值