SQL Server编程(01)流程控制

批处理

应用程序向SqlServer发送的一组命令,Sql Server会将其编译成一个可执行单元,称为执行计划,执行计划中的语句每次执行一条。

每个不同的批处理用GO命令分割。GO命令不是SQL语句,它是告诉SSMS将GO之前的语句作为批处理一起发送给数据库引擎。

注意:GO命令不能和其它SQL命令写在同一行上!局部变量的作用域限定在一个批处理中,不可以在GO后面引用,否则报错!

另外,一次提交多个批处理时,一个批处理出错,只影响其本身继续执行,而不会影响下一个批处理的执行。

 

语句块

T-SQL中使用BEGIN……END来指定语句块。

注意:语句块中声明的变量,其作用域是在整个批处理中,也就是说,在BEGIN……END中定义的变量,可以在END之外进行访问,直到遇见GO。

BEGIN
    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

 

posted @ 2015-10-28 09:46  拓荒者FF  阅读(1680)  评论(1编辑  收藏  举报