SQL中循环和条件语句

 1 1、if语句使用示例:
 2      declare @a int
 3      set @a=12
 4      if @a>100
 5         begin
 6             print @a
 7         end    
 8     else
 9         begin
10             print 'no'
11         end
12 
13 2、while语句使用示例:
14       declare @i int
15       set @i=1
16       while @i<30
17             begin
18             insert into test (userid) values(@i)
19             set @i=@i+1
20         end
21  设置重复执行SQL语句或语句块的条件。只要指定的条件为真,就重复执行语句。可以使用BREAK   和CONTINUE关键字在循环内部控制WHILE循环;
22 
23 3、临时表和try
24      --增加临时表
25     select * into #csj_temp from csj
26     --删除临时表 用到try
27     begin try   --检测代码开始
28             drop table #csj_temp
29     end try
30 
31     begin catch --错误开始
32     end catch
33 
34 4、游标循环记录
35     declare @temp_temp int
36     --创建游标 --Local(本地游标)
37     DECLARE aaa CURSOR for select House_Id from             House_House where Deleted=0 or deleted is null
38     --打开游标
39     Open aaa
40     --遍历和获取游标
41     fetch next from aaa into @temp_temp
42     --print @@fetch_status=0
43     begin
44     select * from House_monthEnd where House_Id=@temp_temp
45     fetch next from aaa into @temp_temp --取值赋给变量
46     end
47     --关闭游标
48     Close aaa
49     --删除游标
50     Deallocate aaa
原文地址:https://www.cnblogs.com/slmdr9/p/5850222.html