当前位置:Gxlcms > 数据库问题 > SQL Server编程(01)流程控制

SQL Server编程(01)流程控制

时间:2021-07-01 10:21:17 帮助过:19人阅读

declare @str nvarchar(50) set @str=abc print(@str) END print(@str) --此处可以正常访问 go print(@str) --此处报错:必须声明标量变量 "@str"。

 

 

条件语句

IF…ELSE…语句

以下代码纯属演示:

declare @num int
set @num=3

if(@num=1)
    begin
        --这里可以写多行代码
        --如果是一行,可以省略begin...end
        print num=1
    end
else if(@num=2)
    --此处只有一行代码,省略begin...end
    print num=2
else
    print num不等于1,也不等于2

 

 

case…when…then…end语句

貌似只能用在select语句中?两种用法:

第一种:

declare @num int
set @num=3
select 
    case @num
        when 1 then num=1
        when 2 then num=2
        else num不等于1,也不等于2
    end as col

 

第二种:

declare @num int
set @num=3
select 
    case    --case后面不写表达式,判断表达式写在when后面
        when @num=1 then num=1
        when @num=2 then num=2
        else num不等于1,也不等于2
    end as col

 

 

貌似只能用在select语句中?我试着把case…when…then…end脱离select使用,但没有成功……

 

循环语句

while循环

直接来一个简单的例子吧:

declare @num int
set @num=3
while(@num>0)    --括号貌似也不是必需的
    begin
        print @num
        set @num=@num-1
    end
go

 

 

使用goto语句实现循环

goto语句其实是用来跳转的,据说乱用goto会把代码变得比意大利面更乱,因此许多编程语言中的goto基本都不怎么用。

在T-SQL中,我们可以使用goto来实现循环的处理,代码如下:

declare @num int
set @num=3
lb:    --标记,名字可以自己起
print @num
if(@num>1)
begin
    set @num-=1;
    goto lb
end

 

SQL Server编程(01)流程控制

标签:pos   sql   tle   多个   nbsp   varchar   代码   否则   局部变量   

人气教程排行