第二章 课后简答

--第二章课后解答
--创建数据库
use master

if exists(SELECT * FROM sysdatabases WHERE name='Library')
DROP DATABASE Library
CREATE DATABASE Library
on PRIMARY
(
NAME='Library_data',
FILENAME='D:\project_data.mdf',
SIZE=5mb,
FILEGROWTH=15%
)
LOG on
(
NAME='S2226_log',
FILENAME='D:\project_log.ldf',
SIZE=5mb,
FILEGROWTH=15mb
)


--创建图书信息表Book
use Library
CREATE TABLE Book
(
BID nvarchar(20) not null,
BName nvarchar(20) not null,
Author nvarchar(20) not null,
PubComp nvarchar not null,
PubDate datetime not null,
BCount int not null,
Price money not null
)


--创建读者信息表Reader
use Library
create table Reader
(
RID nvarchar(20) not null,
RName nvarchar(20) not null,
LendNum int not null,
RAddress nvarchar(100)not null
)


--创建图书借阅表Borrow
use Library
create table Borrow
(
RID nvarchar(20) not null,
BID nvarchar(20) not null,
LendDate datetime not null,
WillDate datetime not null,
ReturnDate datetime not null
)


--创建罚款记录表Penalty
use Library
create table Penalty
(
RID nvarchar(20) not null,
BID nvarchar(20) not null,
PDate datetime not null,
PType int not null,
Amount money not null
)


--添加约束
--图书信息表Book
-- 添加主键约束将BID 作为主键
alter table Book
add constraint pk_BID primary key (BID)


--必须以"ISBN"开头
alter table Book
add constraint ck_BID CHECK(BID='ISBN%')


--出版日期,必须小于当前日期
alter table Book
add constraint ck_PubDate CHECK(PubDate=1)


--单价必须大于0
alter table Book
add constraint ck_Price CHECK(Price>0)


--读者信息表Reader
--添加主键约束将RID 作为主键
alter table Reader
add constraint pk_RID primary key (RID)


--以借数量,必须大于0
alter table Reader
add constraint ck_LendNum CHECK(LendNum>0)


--图书借阅表Borrow
--读者信息表的外键
alter table Borrow 
add constraint fk_RID foreign key (RID) references Reader(RID)


--图书信息表的外键
alter table Borrow 
add constraint fk_BID foreign key (BID) references Reader(BID)


-- 添加借阅日期 复合主键将LendDate作为主键
alter table Borrow
add constraint pk_LendDate primary key (LendDate)


--应归还日期,必须大于等于借阅日期,默认值为借阅日期+1个月
alter table Borrow
add constraint df_WillDate 
default(DateAdd(mm,1,getdate())) for WillDate

--罚款记录表Penalty
 -- 复合主键,读者信息表的外键
alter table Penalty
add constraint fk_RIDd foreign key (RID) references Reader(RID)

-- 复合主键 ,图书信息表的外键 
alter table Penalty 
add constraint fk_BIDd foreign key (BID) references Book(BID)


-- 添加复合主键,将PType作为主键
alter table Penalty
add constraint pk_PDate primary key (PDate)


-- 罚款日期, 默认值为当前日期  
alter table Penalty
add constraint df_PDate default(GetDate()) for PDate


-- 罚款类型 ,1- 延期 ,2-损坏,  3- 丢失 
alter table Penalty
add constraint CK_PType  check (1='延期'or 2='损坏' or 3='丢失')

-- 罚款金额 ,必须大于0 
alter table Penalty
add constraint CK_Amount  check (Amount>0)


你可能感兴趣的:(第二章 课后简答)