您当前的位置: 首页 >  sql

川川菜鸟

暂无认证

  • 4浏览

    0关注

    969博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

sqlsever2019:控制流全解

川川菜鸟 发布时间:2021-12-26 12:09:25 ,浏览量:4

文章目录
    • 一、begin..end语句
    • 二、if ...else 语句
    • 三、case语句
    • 四、while语句
      • 4.1 有限循环
      • 4.2 无限循环
    • 五、break语句
    • 六、return 语句
    • 七、goto语句
    • 八、waitfor语句

一、begin…end语句

BEGIN … END 用来设定一个程序块,将在 BEGIN … END 内的所有程序视为一个单行。 BEGIN … END 经常在条件语句句 IF … ELSE 中使用。在 BEGIN… END 可嵌套另外BEGIN… END 来定义另一程序块,语法如下:

begin
{
sql语句
}
end
二、if …else 语句

这个很简单,直接举个例子说明。 比如段比较变量 的大小,并将结果打印出来:

declare @a int ,@b int,@c int
select @a=10,@b=12,@c=15
if @a>@b
print 'a大于b'
else if @b>@c
print 'b大于c'
else 
print 'c大于b'

演示: 在这里插入图片描述 或者使用set语句,这样只能单个赋值:

declare @a int ,@b int,@c int
--select @a=10,@b=12,@c=15
set @a=10
set @b=12
set @c=15
if @a>@b
print 'a大于b'
else if @b>@c
print 'b大于c'
else 
print 'c大于b'

演示: 在这里插入图片描述

三、case语句

学过c语言的应该很了解case语句了,所以我就不讲太多了,举个例子说明即可。 假设我们有数据表如下: 在这里插入图片描述 SQL遍历条件并在满足第一个条件时返回值:

SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN "The quantity is greater than 30"
    WHEN Quantity = 30 THEN "The quantity is 30"
    ELSE "The quantity is under 30"
END AS QuantityText
FROM OrderDetails; 
四、while语句 4.1 有限循环

while语句就是只要条件为真就会一直执行。语法如下:

WHILE condition
BEGIN
   {...statements...}
END

比如我要做一个打印一到十的循环:

declare @counter int
set @counter=1
while ( @counter             
关注
打赏
1665165634
查看更多评论
0.0508s