SQL Server —— While语句循环

一:简介

while 循环是有条件的循环控制语句。满足条件后,再执行循环体中的SQL语句

while: break, 如果有多条语句可以在while后面添加begin-end。关于while的语法

while(条件)
-- begin
-- 语句1
-- 语句2
-- break 根据情况是否添加break
-- end

 二 关于While的实例1

把10条数据添加一个表中

create table S1
(
    id int not null primary key identity(1,1),
    name varchar(10) not null default ('')
)
declare @count int
set @count = 0
while(@count<10)
    begin
    set @count = @count + 1
    insert into S1(name) values ('鲁班'+ CONVERT(varchar(10), @count)+'号')
    end
select * from S1

执行后效果图如下

 

三 关于while循环的实例2 

循环例子 把成绩csharp小于60 修改成60

while(1=1) 死循环,C#条件比较时1==1,但是t-sql比较1=1

declare @stuid int ,@csharp int -- 学号和C#成绩
while(1=1)
	begin 
		-- 先查询成绩小于60的学生 把学号和cs成绩赋值给对应的变量
		select top 1 @stuid = StudentId,@csharp = CSharp from ScoreList where CSharp < 60
		-- 找出成绩小于60的个数,如果个数小于0 证明没有小于60
		if((select count(*)from ScoreList where CSharp<60 )>0)
			-- 更新成绩
			update ScoreList set CSharp = 60 where StudentId = @stuid
		else --没有小于60 跳出循环
			break
		end
select * from ScoreList

 四 总结

1 有限次数的循环 通过一个变量在循环体里面每次加一,直到循环条件不成立的时候跳出循环
2 没有确定次数的循环,通过横成立条件进行循环 通过break跳出循环体  

相关推荐

  1. 【C语言】分支循环语句

    2024-02-22 15:30:01       33 阅读
  2. Py-While循环语句

    2024-02-22 15:30:01       33 阅读
  3. 【Python基础】循环语句

    2024-02-22 15:30:01       31 阅读
  4. Python循环语句

    2024-02-22 15:30:01       41 阅读
  5. 分支和循环语句

    2024-02-22 15:30:01       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-22 15:30:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-22 15:30:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-22 15:30:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-22 15:30:01       20 阅读

热门阅读

  1. el-select加上搜索查询时,限制开头空格输入

    2024-02-22 15:30:01       32 阅读
  2. 微众银行:始于数字原生,立于普惠金融

    2024-02-22 15:30:01       27 阅读
  3. 主流无人机开源飞控

    2024-02-22 15:30:01       33 阅读
  4. 大模型中的token是什么?

    2024-02-22 15:30:01       29 阅读
  5. windows命令行加入与移除管理员组

    2024-02-22 15:30:01       31 阅读
  6. SpringBoot项目启动后执行指定方法的四种实现

    2024-02-22 15:30:01       28 阅读
  7. react中useState、setState、usemeno、meno区别

    2024-02-22 15:30:01       31 阅读