SqlServer中循環和條件語句


SqlServer中循環和條件語句


   --                                  ╔════════╗    
  -- ===============================  ║ if語句使用示例 ║    
  --                                  ╚════════╝     
            declare @a int    
            set @a=12    
            if @a>100    
               begin    
                   print @a    
               end    
            else    
               begin    
                   print 'no'    
               end    
  --                                  ╔══════════╗    
  -- ===============================  ║ while語句使用示例  ║    
  --                                  ╚══════════╝  
declare @i int   
set @i=1   
while @i<30   
   begin   
   insert into test (userid) values(@i)   
   set @i=@i+1   
end  
   
-- 設置重複執行 SQL 語句或語句塊的條件。只要指定的條件爲真,就重複執行語句。可使用 BREAK 和 CONTINUE 關鍵字在循環內部控制 WHILE 循環中語句的執行。 本條爲之前從網上查找獲取!  
   
   
  --                                   ╔════════╗    
  -- ================================  ║  臨時表和try   ║    
  --                                   ╚════════╝     
     
      -- 增長臨時表    
       select * into #csj_temp from csj    
            
       -- 刪除臨時表 用到try    
        begin try    -- 檢測代碼開始    
             drop table #csj_temp    
        end try    
     
        begin catch  -- 錯誤開始    
        end catch   
   
   
 --                                  ╔═════════╗    
 -- ===============================  ║ 遊標循環讀記錄   ║    
 --                                  ╚═════════╝     
              
            declare @temp_temp int    
            --declare @Cur_Name    
            --@Cur_Name="aaa"    
            --------------------------------- 建立遊標  --Local(本地遊標)    
            DECLARE aaa CURSOR for select House_Id from House_House where Deleted=0 or deleted is null    
            ----------------------------------- 打開遊標    
              Open aaa    
            ----------------------------------- 遍歷和獲取遊標    
                   
            fetch next from aaa into @temp_temp    
            --print @temp_temp    
            while @@fetch_status=0    
            begin    
              --作你要作的事      
              select * from House_monthEnd where House_Id=@temp_temp    
     
              fetch next from aaa into @temp_temp  -- 取值賦給變量    
     
             --     
            end    
     
            ----------------------------------- 關閉遊標    
              Close aaa    
            ----------------------------------- 刪除遊標    
              Deallocate aaa    
            --        
   
   ide