码迷,mamicode.com
首页 > 数据库 > 详细

SQL里面的while 循环

时间:2015-03-19 23:25:20      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

--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

 

SQL里面的while 循环

标签:

原文地址:http://www.cnblogs.com/dianshen520/p/4352005.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!