SQLServer数据库应用与开发:第九章上机

代码及解释

9.1:

create procedure StuInfo3
as
select studentno,sname,birthdate,phone
from student
where studentno like '18%'
go
exec StuInfo3

9.2

create procedure ScoreInfo
as
select student.studentno,sname,sex,cname,final
from student,course,score
where student.studentno=score.studentno and score.courseno=course.courseno
go
exec ScoreInfo

9.3

if exists(
select name from sysobjects
where name= 'stu_age' and type= 'p'
)
drop procedure stu_Age
go

create procedure stu_Age 
@studentno nvarchar(10),@age int output
as
declare @errorvalue int
set @errorvalue=0
select @age=year(GETDATE())-year(birthdate)
from student
where studentno=@studentno
if(@@ERROR<>0)
	set @errorvalue=@@ERROR
return @errorvalue
go

declare @average int
exec stu_age '1',@age=@average output
select @average
  1. procedure相当于函数,有两个参数,在函数体可以对参数进行设置,代码中设置了@age=年龄,便于返回;@studentno用于匹配
  2. @@error不等于0说明出错了,返回的是错误号
  3. @average用于接收返回来的@ave
  4. type='p’表明为prodecure
    9.4
create trigger stu_insert
on student
after insert
as
print '你插了一条新纪录'
go

9.5

CREATE TRIGGER TR_ScoreCheck
ON score
FOR INSERT, UPDATE
AS
IF UPDATE(final )
PRINT 'AFTER触发器开始执行……'
BEGIN
DECLARE @ScoreValue real
SELECT @ScoreValue=(SELECT final FROM inserted)
IF @ScoreValue>100 OR @ScoreValue<0
PRINT '输入的分数有误,请确认输入的考试分数!'
END
GO
  1. insert和update语句激活相应的触发器之后,所有被添加或被更新的记录都被存到inserted表中
  2. delete和update语句激活相应的触发器之后,所有被删除的记录都被存到deleted表中
  3. for相当于after

9.6

if exists(select name from sysobjects where name='dela' and type='tr')
drop trigger dela
go
create trigger dela
on course
after delete
as
print'不能删除'
  1. type='tr’表示为trigger

猜你喜欢

转载自blog.csdn.net/m0_53438035/article/details/125005535