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

 

posted on 2018-12-13 22:18  绅士狼  阅读(686)  评论(0编辑  收藏  举报

导航