SQL sever 约束

/*建库*/
use master
go
if exists(select * from sysdatabases where name = 'StudentDB')
create database StudentDB
on primary
(
name = 'StudentDB_data',
filename = 'E:\DATASTORE\StudentDB_data.mdf',
size = 10MB,
filegrowth = 1MB
)
log on
(
name = 'StudentDB_log',
filename = 'E:\DATASTORE\StudentDB_log.ldf',
size = 10MB,
filegrowth = 1MB
)
go

/*建学生表*/
use StudentDB
go
if exists(select * from sysobjects where name = 'Students')
drop table Students
go
create table Students
(
Id int identity(100,1) primary key,
Name varchar(10) not null,
Gender char(2) default('男'),
Age int not null,
ClassId int not null
)
go


/*插入*/
use StudentDB
go
insert into Students(Name, Gender, Age, ClassId)values('haode', '男', 200, 1)
insert into Students(Name, Gender, Age, ClassId)values('wangwu', default, 30, 1)
insert into Students(Name, Gender, Age, ClassId)values('lisi', '男', 10, 1)
insert into Students(Name, Gender, Age, ClassId)values('zhangsan',  '男', 20, 2)
go


/*查询*/
use StudentDB
go
select * from Students
go


/*建班级表*/
use StudentDB
go
if exists(select * from sysobjects where name = 'Classes')
drop table Classes
go
create table Classes
(
Id int identity(1,1) primary key,
Name varchar(10) not null
)
go

/*插入*/
use StudentDB
go
insert into Classes(Name)values('计算机')
insert into Classes(Name)values('软件')
go

/*查询*/
use StudentDB
go
select * from Classes
go


/*主键约束*/
use StudentDB
go
if exists(select * from sysobjects where name = 'pk_Id')
alter table Students
drop constraint pkId
alter table Students
add constraint pk_Age primary key(Id)
go

/*唯一约束*/
use StudentDB
go
if exists(select * from sysobjects where name = 'uq_Age')
alter table Students
drop constraint uq_Age
go
alter table Students
add constraint uq_Age unique(Age)
go

/*检查约束*/
use StudentDB
go
if exists(select * from sysobjects where name = 'ck_Age')
alter table Students
drop constraint ck_Age
go
alter table Students
add constraint ck_Age check(Age between 0 and 99)
go

/*默认值约束*/
use StudentDB
go
if exists(select * from sysobjects where name = 'df_Gender')
alter table Students
drop constraint df_Gender
go
alter table Students
add constraint df_Gender default('男')for Gender
go

/*外键约束*/
use StudentDB
go
if exists(select * from sysobjects where name = 'fk_ClassId')
alter table Students
drop constraint fk_ClassId
go
alter table Students
add constraint fk_ClassId foreign key(ClassId) references Classes(Id)
go

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值