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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM