用循环实现表行遍历是SQL语句开发过程中常见的实际操作,其中MS SQL尤为重要。本文 将介绍如何在MSSQL中使用循环来实现表的行遍历操作,并以实际示例进行讲解。
首先,定义一个表变量,用于记录学生分数,表结构如下:
1 |
declare @StudentScore table(StudentId int, Score int)<br> |
接下来,使用INSERT INTO语句向表中插入数据:
1 |
INSERT INTO @StudentScore(StudentId, Score)<br>VALUES(1, 89),</br>(2, 72),<br>(3, 97),</br>(4, 69),<br>(5, 82)</br> |
最后,遍历@StudentScore表,使用WHILE循环语句进行行遍历:
1 |
DECLARE @StudentId int<br>DECLARE @Score int</br><br>SET @StudentId = (SELECT MIN(StudentId) FROM @StudentScore)</br>WHILE @StudentId IS NOT NULL<br>BEGIN</br> SELECT @Score = Score FROM @StudentScore WHERE StudentId = @StudentId<br> PRINT @StudentId + ' ' + @Score </br> SET @StudentId = (SELECT MIN(StudentId) FROM @StudentScore WHERE StudentId > @StudentId)<br>END</br> |
循环结束后,终端打印的结果如下:
1 89
2 72
3 97
4 69
5 82
以上就是在MSSQL中使用循环实现表行遍历的示例,根据实际业务需要,可以使用CURSOR和WHILE循环结合使用来遍历表中的数据,从而满足实际业务需求,提高程序的开发效率。