为什么 mysql 存储过程中的 num 总是输出 0
使用存储过程来统计特定条件的学生人数时,遇到的问题是输出的 num 永远为 0。这是因为在声明存储过程变量时缺少默认值。
具体来说,当声明变量 tempsno 时没有指定默认值。当从 sc 表中获取 student 编号 (sno) 和分数 (score) 时,tempsno 的值保持为 null。因此,当比较 tsno 和 tempsno 时,始终返回 null,无法进入统计条件的 if 语句块。
要解决此问题,需要在声明 tempsno 变量时添加默认值,例如:
declare tempsno varchar(30) default '';
通过设置默认值,存储过程可以正确跟踪从 sc 表中获取的 sno,并在满足条件时正确增加 num。修改后的存储过程如下:
begin declare tSno varchar(30); declare tScore numeric(10,2); declare TempSno varchar(30) default ''; declare done int default 0; declare Num int default 0; declare getStudent cursor for select Sno, Score from SC order by Sno; declare continue handler for SQLSTATE '02000' set done = 1; open getStudent; repeat fetch getStudent into tSno,tScore; if(tScore<60) then if(tSno!=TempSno) then set Num = Num + 1; set TempSno = tSno; end if; end if; until done end repeat; select Num; close getStudent; drop table OrderTable; end // delimiter ; call countNum();
修改后,num 将正确输出满足条件的学生人数。
以上就是MySQL 存储过程中 Num 总是输出 0:为什么 TempSno 变量没有默认值?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号