当前位置:文档之家› 实验五 存储过程和触发器(计科)

实验五 存储过程和触发器(计科)

实验五:触发器和存储过程
一、实验目的:理解触发器和存储过程的含义,掌握用SQL语句实现触发器和存储过程的编写,并初步掌握什么情况下使用事务。

二、预习要求:存储过程和触发器的相关概念,事务的相关概念,编写相应的SQL语句。

三、实验内容:
有一个小型的图书管理数据库,包含的表为:
bookstore(bookid,bookname,bookauthor,purchasedate,state);
--图书库存表
borrowcard(cardid,ownername);--借书证表
borrowlog(cardid,bookid,borrowdate,returndate);--借书记录表
写一个存储过程,实现借书操作,要求有事务处理。

(1)读者借书,要先设置书籍不在库标志state(借出),然后增加借书记录,在同一事务中完成。

(2)要求在事务执行过程中引入错误触发事件,以此体会事务的错误保护机制和事务编程的作用。

(3)要求用触发器实现表的完整性控制。

四、完成情况(附上设计的SQL语句)。

------触发器和存储过程
------触发器和存储过程
CREATE DATABASE BOOK1
go
use BOOK1
CREATE TABLE BOOKSTORE(Bookid nvarchar(10),Bookname
nvarchar(10),Bookauthor nvarchar(10),purchasedate datetime,state Nvarchar(10),primary key(Bookid))
Create table Borrowcard(Cardid int,ownername nvarchar(10),primary
key(Cardid))
Create table Borrowlog(Cardid int,Bookid nvarchar(10),borrowdate datetime,returndate datetime
,primary key(Cardid,Bookid))
insert into Borrowcard values(12,'wyb')
insert into Borrowcard values(123,'wyb')
insert into Borrowcard values(1,'wyb')
insert into Bookstore values(1,'数据库','王珊','2012-04-23','存在') insert into Bookstore values(2,'数据结构','珊','2012-11-23','存在') insert into Bookstore values(3,'数据结构','珊','2011-1-23','存在') insert into Bookstore values(11,'数据库','王珊','2009-10-23','存在') insert into Bookstore values(12,'数据结构','珊','2001-11-23','存在') insert into Bookstore values(13,'数据结构','珊','2013-12-23','存在')
----借书存储过程
create proc borrow1
@bookid nvarchar(10),
@cardid int
as
begin transaction
insert into Borrowlog(Cardid,Bookid,borrowdate,returndate)
values(@cardid,@bookid,getdate(),null)
if exists(select*from bookstore,Borrowcard where bookid=@bookid and state='存在'and cardid=@cardid)
begin
update bookstore set state='不存在'where bookid=@bookid
commit transaction
end
else
begin
if exists(select*from bookstore where bookid=@bookid and state='不存在')
Print'不存在该书'
if not exists(select*from borrowcard,bookstore where cardid=@cardid) Print'没有此用户'
rollback transaction
End
exec borrow1'3',12
exec borrow1'3',123
exec borrow1'2',123
drop proc borrow1----删除存储过程
Create trigger insert_borrowlog
on Borrowlog after insert
as
declare@borrowdate datetime
,@returndate datetime
select@borrowdate=borrowdate,@returndate=returndate from inserted
if(@borrowdate>@returndate)
print'借书时间不可晚于还书时间'
rollback
select*from bookstore
insert into Borrowlog values(12,'1','2013-06-06','2012-05-5')
五、思考题:
如何通过系统的设置实现类似的功能,而不需触发器?
答:通过定义存储过程或者设置外键约束等方法。

六、实验总结:
答:对存储过程非常不熟悉,做起来特别生硬。

所以我们应该多做上机练习,熟悉sql的语言环境,多看书,以提升自己各方面能力。

相关主题