SQL Server存储过程与触发器课堂练习及答案 下载本文

内容发布更新时间 : 2024/5/3 1:20:11星期一 下面是文章的全部内容请认真阅读。

存储过程与触发器课堂练习及答案

1. 创建一个存储过程,显示所有价格在15美元以下的书的书名,类型,价格。 CREATE PROCEDURE show_title AS

SELECT title,type,price FROM titles

WHERE price < 15 GO

EXEC show_title

2. 把价格作为参数,创建一个能显示在某两个指定价格之间的书的书名,类型,价格。 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

3. 使用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

4. 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

5. 修改练习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

6. 创建一个存放书的编号、书名、类型、价格、对应作者的编号、姓名、电话、住址的视

图。 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

7. 为这个视图创建一个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, @price = price, @au_id = au_id, @phone = phone ,@address = address from inserted

update titles set price = @price where title_id = @title_id

update authors set phone = @phone, address = @address where au_id = @au_id go

8. 添加测试数据。更新v_titledetail,把书编号为‘LI1234’的书的价格改为200,该书作

者的电话该为‘02512345678’ update v_titledetail

set price = 200, phone = '025123445678' where title_id = 'LI1234' 9.