我的漫漫程序之旅

          專注于JavaWeb開發
          隨筆 - 39, 文章 - 310, 評論 - 411, 引用 - 0
          數據加載中……

          使用Transact-SQL 遍歷結果集

          使用 Transact-SQL 語句循環結果集

          有三種方法使用可以通過使用 Transact-SQL 語句遍歷一個結果集。

          一種方法是使用 temp 表。 使用這種方法您創建的初始的 SELECT 語句的"快照"并將其用作基礎"指針"。 例如:
          /********** example 1 **********/ 

          declare @au_id char11 )

          set rowcount 0
          select * into #mytemp from authors

          set rowcount 1

          select @au_id = au_id from #mytemp

          while @@rowcount <> 0
          begin
              
          set rowcount 0
              
          select * from #mytemp where au_id = @au_id
              
          delete #mytemp where au_id = @au_id

              
          set rowcount 1
              
          select @au_id = au_id from #mytemp<BR/>
          end
          set rowcount 0
                  
          第二個的方法是表格的一行"遍歷"每次使用 Min 函數。 此方法捕獲添加存儲的過程開始執行之后, 假設新行必
          須大于當前正在處理在查詢中的行的唯一標識符的新行。 例如:

          /********** example 2 **********/ 

          declare @au_id char11 )

          select @au_id = min( au_id ) from authors

          while @au_id is not null
          begin
              
          select * from authors where au_id = @au_id
              
          select @au_id = min( au_id ) from authors where au_id > @au_id
          end
          注意 : 兩個示例 1 和 2,則假定源表中的每個行唯一的標識符存在。 在某些情況下,可能存在沒有唯一標識符。 如果是這種情況,您可以修改 temp 表方法使用新創建的鍵列。 例如:
          /********** example 3 **********/ 

          set rowcount 0
          select NULL mykey, * into #mytemp from authors

          set rowcount 1
          update #mytemp set mykey = 1

          while @@rowcount > 0
          begin
              
          set rowcount 0
              
          select * from #mytemp where mykey = 1
              
          delete #mytemp where mykey = 1
              
          set rowcount 1
              
          update #mytemp set mykey = 1
          end
          set rowcount 0


          posted on 2009-01-08 11:35 々上善若水々 閱讀(1723) 評論(0)  編輯  收藏 所屬分類: 數據庫

          主站蜘蛛池模板: 宝兴县| 商城县| 饶河县| 饶阳县| 东海县| 措美县| 固始县| 壶关县| 河池市| 西城区| 明光市| 拜城县| 准格尔旗| 富民县| 中宁县| 华阴市| 宝坻区| 中超| 巴彦县| 抚顺市| 海城市| 南涧| 玉龙| 凤凰县| 宜丰县| 沈阳市| 宕昌县| 长宁县| 固镇县| 浮山县| 定安县| 长治市| 巫溪县| 淄博市| 宁远县| 高碑店市| 江孜县| 都兰县| 昌乐县| 绍兴县| 隆回县|