SQL实验报告
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
实验四触发器实验
(一)after触发器
(1)在lineitem表上定义一个after触发器,当修改列项目extendedprice discount tax时,要把orders表的totalprice一起修改,以保证数据一致性
CREATE TRIGGER trig_lineitem_price_update on lineitem
for update
as
begin
if (UPDATE(extendedprice) or UPDATE(tax) or UPDATE(discount))
begin
--声明游标变量指向inserted表
declare cursor_inserted cursor read_only
for select orderkey,linenumber,extendedprice,discount,tax from inserted -- 声明变量获取查找信息
declare @orderkey int,@linenumber int,@extendedprice real,@discount real,@tax real -- 打开游标
open cursor_inserted
-- 读取游标
fetch next from cursor_inserted into @orderkey,@linenumber,@extendedprice,@discount,@tax
while @@FETCH_STATUS=0
begin
--声明一个变量保存重新计算的新价格
declare @new_totalprice real
select @new_totalprice=@extendedprice*(1-@discount)*(1+@tax)
--用新的总价格变量更新orders表的totalprice
update orders set totalprice=@new_totalprice where orderkey=@orderkey fetch next from cursor_inserted into @orderkey,@linenumber,@extendedprice,@discount,@tax
end
deallocate cursor_inserted
end
end
(2)在lineitem表上定义一个after触发器,当增加一项订单明细时,
自动修改orders表的totalprice,以保证数据一致性
CREATE TRIGGER trig_lineitem_price_insert on lineitem
for insert
as
begin
--声明游标变量指向inserted表
declare cursor_inserted cursor read_only
for select orderkey,linenumber,extendedprice,discount,tax from inserted -- 声明变量获取查找信息
declare @orderkey int,@linenumber int,@extendedprice real,@discount real,@tax real -- 打开游标
open cursor_inserted
-- 读取游标
fetch next from cursor_inserted into
@orderkey,@linenumber,@extendedprice,@discount,@tax
while @@FETCH_STATUS=0
begin
--声明一个变量保存重新计算的新价格
declare @new_totalprice real
select @new_totalprice=@extendedprice*(1-@discount)*(1+@tax)
--用新的总价格变量更新orders表的totalprice
update orders set totalprice=totalprice+@new_totalprice where
orderkey=@orderkey
fetch next from cursor_inserted into
@orderkey,@linenumber,@extendedprice,@discount,@tax
end
deallocate cursor_inserted
end
(3) 在lineitem表上定义一个after触发器,当删除一项订单明细记录时,
自动修改orders表的totalprice,以保证数据一致性
CREATE TRIGGER trig_lineitem_price_delete on lineitem
for delete
AS
begin
--声明游标变量指向deleted表
declare cursor_deleted cursor read_only
for select orderkey,linenumber,extendedprice,discount,tax from deleted -- 声明变量获取查找信息
declare @orderkey int,@linenumber int,@extendedprice real,@discount real,@tax real -- 打开游标
open cursor_deleted
-- 读取游标
fetch next from cursor_deleted into
@orderkey,@linenumber,@extendedprice,@discount,@tax
while @@FETCH_STATUS=0
begin
--声明一个变量保存重新计算的新价格
declare @new_totalprice real
select @new_totalprice=@extendedprice*(1-@discount)*(1+@tax)