这里有一个单位表
unitT
Id | name |
1 | 单位1 |
2 | 单位2 |
有一个评分项目表
itemT
Id | name |
1 | 项目1 |
2 | 项目2 |
有一个单位得分表
scoreT
Id | unitId | itemid | score |
1 | 1 | 1 | 20 |
2 | 2 | 1 | 50 |
3 | 1 | 2 | 30 |
4 | 2 | 2 | 60 |
现在需要遍历所有单位将他们的分数查询出来,就用循环遍历的方法
当前我使用的是游标方法,还有其他遍历方式。
--定义变量,用于存储当前被遍历到的值
declare @a nvarchar(40);
--递归,首先需要递归的空间,定义一个游标指向这个空间
declare mycursor cursor for select id from unitT
--打开游标
open mycursor
--开始遍历,将下一行的数据存入两个变量中
fetch next from mycursor into @a
while (@@fetch_status=0)--如果下一行还有数据
begin--开始遍历
select * from scoreT where unitId=@a
fetch next from mycursor into @--再下一行
end--遍历结构结束
close mycursor--关闭游标
deallocate mycursor--删除游标
--遍历完成