TRY-CATCH结构
语法:
BEGIN TRY
SQL语句…
END TRY
BEGIN CATCH
错误处理语句…
END CATCH
例:
使用存储过程实现由用户输入学生的学号及课程名称,根据 输入的信息,显示相应的成绩,如果成绩小于60分,则向
ReExam(StuID,CourseID,Grade)表中插入一条记录。
-- 改进的程序
CREATE PROC prcGetScore @StuID char(10),
@CourseName varchar(20)
AS
BEGIN TRY
DECLARE @Grade int SET @Grade = 0
DECLARE @CourseID int SET @CourseID = 0
SELECT @Grade = Grade,@CourseID = CourseID
FROM SC JOIN Course
ON SC.CourseID = Course.CourseID
WHERE StuID = @StuID and CourseName=@CourseName
IF @Grade < 60
insert into ReExam
values(@StuID,@CourseID,@Grade)
END TRY
BEGIN CATCH
PRINT ‘输入数据有误,学号以A,B或Z打头,后跟5位数字’
END CATCH
IF EXISTS语句
if exists语句用来判断某条信息是否存在
例:例如,查询1号学生的成绩之前可以先判断1号学生是否存
在,存在则查询,不存在提示用户该学生不存在。
IF EXISTS(SELECT * FROM Student WHERE StuID
= ‘A00001’)
SELECT * FROM SC WHERE StuID=‘A00001’
and CourseID = 1
ELSE
PRINT ’该学生不存在!’
例:输入学生的学号和课程号,查找学生的成绩,如果超过60分,则显示pass,否则显示failed
create proc prcGetScore
@StuID char(10),
@CourseID int
AS
begin try
if exists(select * from SC where StuID = @StuID and CourseID = @CourseID)
begin
declare @Score float
select @Score = Score
from SC
where StuID = @StuID and CourseID = @CourseID
print @Score
end
else
print 'info does not exist!'
end try
begin catch
print 'error'
end catch
exec prcGetScore 'A00001',1 --执行存储过程