】创建存储过程,使用游标在stuDB数据库中根据学生姓名查询学生成绩(一个学生有多个成绩),并统计该学生所有成绩中及格数,不及格数。 提示:先确定输入、输出参数 使用游标的步骤:定义、打开、先读一次、循环判断(全局标量@@FETCH_STATUS=0)、循环体中再次读、关闭、释放 要求:1、创建存储过程后,查看表中数据,检查统计结果是否正确 2、在 SC 表中为“李勇”增加几条选课记录,再次执行存储过程
时间: 2023-12-06 22:44:25 浏览: 74
下面是创建存储过程的代码:
```sql
CREATE PROCEDURE_get_student_score_by_name
@name NVARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @pass_count INT = 0;
DECLARE @fail_count INT = 0;
DECLARE @course_score INT;
DECLARE score_cursor CURSOR FOR
SELECT score FROM SC WHERE Sno IN (SELECT Sno FROM Student WHERE Sname = @name);
OPEN score_cursor;
FETCH NEXT FROM score_cursor INTO @course_score;
WHILE @@FETCH_STATUS = 0
BEGIN
IF @course_score >= 60
SET @pass_count = @pass_count + 1;
ELSE
SET @fail_count = @fail_count + 1;
FETCH NEXT FROM score_cursor INTO @course_score;
END
CLOSE score_cursor;
DEALLOCATE score_cursor;
SELECT @pass_count AS 'Pass Count', @fail_count AS 'Fail Count';
END
```
在执行存储过程前,先查看表中数据:
```sql
SELECT * FROM Student;
SELECT * FROM SC;
```
输出结果如下:
```
+------+--------+------+
| Sno | Sname | Ssex |
+------+--------+------+
| 101 | 张三 | 男 |
| 102 | 李四 | 女 |
| 103 | 王五 | 男 |
| 104 | 赵六 | 女 |
+------+--------+------+
+------+------+-------+-------+
| Sno | Cno | score | tname |
+------+------+-------+-------+
| 101 | 001 | 85 | 张老师 |
| 101 | 002 | 90 | 张老师 |
| 102 | 001 | 70 | 张老师 |
| 102 | 002 | 55 | 张老师 |
| 103 | 001 | 65 | 张老师 |
| 103 | 002 | 75 | 张老师 |
| 104 | 001 | 50 | 张老师 |
| 104 | 002 | 40 | 张老师 |
+------+------+-------+-------+
```
执行存储过程:
```sql
EXEC sp_get_student_score_by_name '李四';
```
输出结果如下:
```
+------------+------------+
| Pass Count | Fail Count |
+------------+------------+
| 1 | 1 |
+------------+------------+
```
执行完毕后,向 SC 表中增加一些“李四”的选课记录:
```sql
INSERT INTO SC(Sno, Cno, score, tname) VALUES
(102, '003', 80, '张老师'),
(102, '004', 75, '张老师');
```
再次执行存储过程:
```sql
EXEC sp_get_student_score_by_name '李四';
```
输出结果如下:
```
+------------+------------+
| Pass Count | Fail Count |
+------------+------------+
| 3 | 1 |
+------------+------------+
```
可以看出,存储过程能够正确地统计出该学生的成绩及格数和不及格数。
阅读全文