SqlServer之代码块相关

转载必需注明出处:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/sqlserver-codeblock/

一、go语句

Go语句是SqlServer中用来表示当前代码块结束提交并确认结果的语句。

Go语句不能和其他Sql命令卸载同一行上!

定义的局部变量作用域局限在定义它的代码快中,如:在go语句前定义的变量在go语句后面则不可用。

如果一次执行多个用go语句分开的代码块时,其中一个代码块出错不会影响其他代码块的执行

 

二、Begin……End语句

T-Sql使用begin…end来指定代码块,但是在begin…end中声明的变量在end结束之后还可以使用,直到遇见go语句

复制代码
1 begin
2 declare @i int=0
3 select @i
4 end
5 select @i
6 go
7 select @i
复制代码

三、If……eles语句

SQL中的If…else语句和其他编程语言中的语法一样,Sql中的if…else可以不用添加括号。另外SQL中还有if exists…else和if not exists…else的用法

复制代码
   --创建临时表@table
 1 declare @table table( Id int)
 2 insert into @table values(1)
 3 if( 1=1) 
 4     select * from @table
 5 else
 6     select 1
 7  
 8 if exists( select * from @table)
 9 begin
10     select * from @table
11 end
12  
13 if not exists( select * from @table)
14 begin
15     select * from @table
16 end
复制代码

四、Case…When…then…else…end语句

Case具有两种格式,简单Case函数和Case搜索函数。

复制代码
1 --简单Case函数
2 CASE sex
3          WHEN '1' THEN '男'
4          WHEN '2' THEN '女'
5 ELSE '其他' END
6 --Case搜索函数
7 CASE WHEN sex = '1' THEN '男'
8          WHEN sex = '2' THEN '女'
9 ELSE '其他' END
复制代码

上面两种格式可以实现相同的功能,但是简单的case相对来说写法比较方便,但是他的功能也就有些限制,如对sex写判断比较的时候就只能选择case搜素函数方式。如下:

1 CASE WHEN sex > 1 THEN '男'
2          WHEN sex < 2 THEN '女'
3 ELSE '其他' END

五、While语句

While循环主要是根据while后边的值来判断循环语句是否继续执行,如下:

1 declare @var_a int = 10
2 while( @var_a > 0)
3 begin
4     select @var_a
5     set @var_a=@var_a-1
6 end

While循环语句通常和游标(cursor)一块使用如:

复制代码
 1 declare MyCursor cursor for select Name from #table --定义游标,游标数据集来源临时表#table
 2 open MyCursor --打开游标以供下面代码使用
 3 fetch next from MyCursor into @name --将游标指向的值赋值给临时变量@name,游标指向下一条数据
 4 while @@FETCH_STATUS=0 --判断游标是否到最后一条记录
 5 begin
 6     select @name
 7     fetch next from MyCursor into @name
 8 end
 9 close MyCursor --关闭游标
10 deallocate MyCursor -- 释放最后的游标引用时
posted @ 2018-10-26 10:02  欧阳宇  阅读(948)  评论(0编辑  收藏  举报