SQL里面的while 循环

--WHILE循环
--特点:
--1.没有True/false,要写条件表达式
--2.也可以嵌套
--3.也可以break,continue
--4.没有{},需要使用begin..end

--如果office不及格的人超过半数(考试题出难了),则给每个人增加2分,循环加,直到不及格的人数少于一半。
go
declare @subjectname nvarchar(50)='office' --科目名称
declare @subjectId int =(select SubjectId from Subject where SubjectName=@subjectname) --科目ID
declare @classid int--指定科目所属于的班级ID
set @classid=(select classid from Subject where SubjectName=@subjectname); --查询指定科目所属于的班级ID
declare @totalNum int --总人数
select @totalNum=COUNT(*) from Student where ClassId=@classid--获取需要参数指定科目考试的总人数
declare @unpassNum int --指定科目没有及格的人数
select @unpassNum=(select COUNT(*) from Result where SubjectId=@subjectId and StudentResult<60) --查询没有通过人次
--循环加分
while(@unpassNum>@totalNum/2)
begin
--执行加分操作
update Result set StudentResult+=2 where SubjectId=@subjectId and StudentResult<=98
--再次统计没有通过的人次
select @unpassNum=(select COUNT(*) from Result where SubjectId=@subjectId and StudentResult<60)
end
go
--------------------------------------------------

------------------------------------------------------
go
declare @subjectname nvarchar(50)='office' --科目名称
declare @subjectId int =(select SubjectId from Subject where SubjectName=@subjectname) --科目ID
declare @classid int--指定科目所属于的班级ID
set @classid=(select classid from Subject where SubjectName=@subjectname); --查询指定科目所属于的班级ID
declare @totalNum int --总人数
select @totalNum=COUNT(*) from Student where ClassId=@classid--获取需要参数指定科目考试的总人数
declare @unpassNum int --指定科目没有及格的人数
--select @unpassNum=(select COUNT(*) from Result where SubjectId=@subjectId and StudentResult<60) --查询没有通过人次
--循环加分
while(1=1)
begin
if(@totalNum/2<(select COUNT(*) from Result where SubjectId=@subjectId and StudentResult<60))
--执行加分操作
update Result set StudentResult+=2 where SubjectId=@subjectId and StudentResult<=98
else
break
end

人的本事不是与生俱来的,不是你掌握了多少,而是当你面对一个未知问题的时候,你能用多少时间来掌握!
原文地址:https://www.cnblogs.com/dianshen520/p/4352005.html