游标练习 【题目】创建存储过程,使用游标在stuDB数据库中根据学生姓名查询学生成绩(一个学生有多个成绩),并统计该学生所有成绩中及格数,不及格数。 提示:先确定输入、输出参数 使用游标的步骤:定义、打开、先读一次、循环判断(全局标量@@FETCH_STATUS=0)、循环体中再次读、关闭、释放 要求:1、创建存储过程后,查看表中数据,检查统计结果是否正确 2、在 SC 表中为“李勇”增加几条选课记录,再次执行存储过程 三、实验步骤
时间: 2023-07-10 10:05:36 浏览: 170
1. 首先创建存储过程,定义输入参数为学生姓名,输出参数为及格数和不及格数。
```
CREATE PROCEDURE select_scores_by_name
@name nvarchar(50),
@pass_count int OUTPUT,
@fail_count int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @score int;
SET @pass_count = 0;
SET @fail_count = 0;
DECLARE score_cursor CURSOR FOR
SELECT score FROM scores WHERE student_name = @name;
OPEN score_cursor;
FETCH NEXT FROM score_cursor INTO @score;
WHILE @@FETCH_STATUS = 0
BEGIN
IF @score >= 60
SET @pass_count = @pass_count + 1;
ELSE
SET @fail_count = @fail_count + 1;
FETCH NEXT FROM score_cursor INTO @score;
END
CLOSE score_cursor;
DEALLOCATE score_cursor;
END
```
2. 然后执行存储过程,输入学生姓名,输出及格数和不及格数。
```
DECLARE @pass_count int;
DECLARE @fail_count int;
EXEC select_scores_by_name '张三', @pass_count OUTPUT, @fail_count OUTPUT;
SELECT @pass_count AS '及格数', @fail_count AS '不及格数';
```
3. 在 SC 表中为“李勇”增加几条选课记录,再次执行存储过程。
```
INSERT INTO sc (student_id, course_id, score) VALUES (3, 1, 80);
INSERT INTO sc (student_id, course_id, score) VALUES (3, 2, 70);
INSERT INTO sc (student_id, course_id, score) VALUES (3, 3, 90);
EXEC select_scores_by_name '李勇', @pass_count OUTPUT, @fail_count OUTPUT;
SELECT @pass_count AS '及格数', @fail_count AS '不及格数';
```
阅读全文