SQL Server存储过程与触发器课堂练习及答案.doc
文本预览下载声明
存储过程与触发器课堂练习及答案
创建一个存储过程,显示所有价格在15美元以下的书的书名,类型,价格。
CREATE PROCEDURE show_title
AS
SELECT title,type,price
FROM titles
WHERE price 15
GO
EXEC show_title
把价格作为参数,创建一个能显示在某两个指定价格之间的书的书名,类型,价格。
CREATE PROCEDURE show_title2
@price1 money,@price2 money
AS
SELECT title,type,price
FROM titles
WHERE price between @price1 and @price2
GO
show_title2 12,20
使用OUTPUT参数,创建一个计算圆柱体体积的存储过程。并执行它。
CREATE PROCEDURE comp_area
@r smallint,
@h smallint,
@result decimal(10,2) OUTPUT
AS
SET @result = PI()*SQUARE(@r)* @h
GO
DECLARE @answer decimal(10,2)
EXECUTE comp_area 2,3, @answer OUTPUT
SELECT The result is: , @answer
A) 建立price_change表,准备用来存放书的价格变化信息,有以下几列:title_id, type, old_price, new_price, change_date, operator。
B) 建立一个更新触发器,一旦titles表发生更新,立即把相关信息存放到price_change表中。
create table price_change
(
title_id varchar(20),
type varchar(20),
old_price money,
new_price money,
change_date datetime,
operator varchar(20)
)
go
create trigger tri_price
on titles
for update
as
insert into price_change
select o.title_id,o.type,o.price,n.price,getdate(),user_name()
from deleted o JOIN inserted n
ON o.title_id = n.title_id
go
update titles set price = price*1.1
修改练习4,使得只有当price列被更新时,才会触发触发器。
create trigger tri_price
on titles
for update
as
if update(price)
begin
insert into price_change
select o.title_id,o.type,o.price,n.price,getdate(),user_name()
from deleted o JOIN inserted n
ON o.title_id = n.title_id
end
go
创建一个存放书的编号、书名、类型、价格、对应作者的编号、姓名、电话、住址的视图。
use pubs
go
create view v_titledetail
as
select t.title_id, title, type, price, a.au_id, au_lname, au_fname, phone, address
from titles t,titleauthor ta,authors a
where t.title_id = ta.title_id and ta.au_id = a.au_id
为这个视图创建一个Instead of更新触发器,把对视图的更新放到触发器里面来做。(假设,我们只允许更新这个视图的某几个列:price, phone, address)
create trigger tri_titledetail
on v_titledetail
instead of update
as
declare @price money,
@phone varchar(20),
@address varchar(40),
@title_id varchar(20),
@au_id varchar(20)
select @title_id = title_id
显示全部