1.存储过程作业:利用存储过程完成图书借阅系统的功能
2.触发器的应用
3.ADO.NET的Connection应用
4.ADO.NET的Command应用
select * from reader
select * from book
select * from borrow
select * from punish
/*
添加借阅信息,输入参数:读者id、书名
1. 图书库存量-1
2. 读者的借阅量:+1
3. 借阅记录的三个日期:采用默认值
*/
create proc sp_borrow(@rid int, @bname nvarchar(50))
as
begin
--根据书名获取书号default '汉族' for nation
alter table borrow add constraint df_1 default getdate() for lendDate --借阅时间
alter table borrow add constraint df_2 default dateadd(dd,7,getdate()) for willDate --应归还时间加7天归还
alter table borrow add constraint df_3 default null for returnDate --默认归还时间为NULL
declare @bid int --书号
select @bid=bid from book where bname=@bname --查询书号
insert into borrow values(@rid, @bid,default,default,default)--插入借书表一条记录
update reader set lendNum = lendNum + 1 where rid=@rid --读者的借阅量:+1
update book set bcount=bcount-1 where bid=@bid --该图书库存量-1
end
execute sp_borrow 2,'天龙八部'
-- drop table t_history
--触发器(也是一种存储过程)案例中用到的数据表
create table t_history --修改名字的记录表
(
id int identity(1,1) primary key,
[sid] int, --学号
oName nvarchar(50), --旧名字
nName nvarchar(50), --新名字
[date] datetime --改名时间
)
create table t_class --班级表
(
cid int identity(1,1) primary key,
cName nvarchar(50),
sCount int --总人数
)
create table t_student --学生表
(
[sid] int identity(1,1) primary key, --学号
sName nvarchar(50), --姓名
cid int --班级编号
)
--触发器
/*
是一种特殊的存储过程,由数据的行为(增删改查)导致某个存储过程自动执行。
分类:DML触发器 + DDL触发器 + 登录触发器 create alter drop
DML触发器 = after触发器 + instead of触发器
after触发器:在执行完增删改操作之后出发
instead of触发器:执行触发器本身,一般用在表or视图上定义
*/
/* DML触发器有两个特殊的表: inserted + deleted 是只读的
1.其中的数据是只读的
2.生命周期随触发器执行结束而结束
inserted:增加 和 修改操作后的数据
deleted: 删除 和 修改前的数据
update:新取代旧
*/
select * from t_class
select * from t_student
--添加新学生时,班级的总人数字段+1
--删除触发器
drop trigger trig_student_insert
create trigger trig_student_insert
on t_student after insert --插入之后执行触发
as
begin
declare @cid int --新增学生对应的班级编号
declare @sCount int -- 该班级的当前总人数
select @cid = cid from inserted --触发器无参数,数据从inserted 或deleted 表中来
select @sCount = sCount from t_class where cid=@cid --将该班级的总人数
set @sCount=@sCount+1 --将该班级的总人数+1
update t_class set sCount=@sCount where cid=@cid --修改该班级的总人数
end
--调用触发器,在学生表插入新的学生属于3号班级(目前3号班级的总人数为0)
insert into t_student values('老顽童',3)
--案例2
truncate table t_history
select * from t_history
select * from t_student
--触发器:修改学生姓名时,将原姓名和现在的姓名都记录在案
--drop trigger trig_update_student
if exists(select * from sysobjects where name='trig_update_student')
drop trigger trig_update_student
go --检查是否重名
create trigger trig_update_student
on t_student after update --检查修改之后执行
as
begin
declare @sid int --改名的学号
declare @oName nvarchar(50) --以前的姓名
declare @nName nvarchar(50) --修改后的姓名
select