Transact-SQL語句遍歷結果集的三種方法


Transact-SQL語句是可以實現遍歷的,有三種方法使用可以通過使用Transact-SQL語句遍歷一個結果集。下面就為您詳細介紹Transact-SQL語句遍歷結果集的幾種方法,供您參考。

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

  1. /**//********** example 1 **********/   
  2.  
  3. declare @au_id char( 11 )  
  4.  
  5. set rowcount 0  
  6. select * into #mytemp from authors  
  7.  
  8. set rowcount 1  
  9.  
  10. select @au_idau_id = au_id from #mytemp  
  11.  
  12. while @@rowcount <> 0  
  13. begin  
  14.     set rowcount 0  
  15.     select * from #mytemp where au_id = @au_id  
  16.     delete #mytemp where au_id = @au_id  
  17.  
  18.     set rowcount 1  
  19.     select @au_idau_id = au_id from #mytemp<BR/> 
  20. end  
  21. set rowcount 0  

第二個的方法是表格的一行"遍歷"每次使用 Min 函數。此方法捕獲添加存儲的過程開始執行之后, 假設新行必須大於當前正在處理在查詢中的行的唯一標識符的新行。例如:

  1. /**//********** example 2 **********/   
  2.  
  3. declare @au_id char( 11 )  
  4.  
  5. select @au_id = min( au_id ) from authors  
  6.  
  7. while @au_id is not null  
  8. begin  
  9.     select * from authors where au_id = @au_id  
  10.     select @au_id = min( au_id ) from authors where au_id > @au_id  
  11. end  

注意 : 兩個示例1和2,則假定源表中的每個行唯一的標識符存在。在某些情況下,可能存在沒有唯一標識符 如果是這種情況,您可以修改temp表方法使用新創建的鍵列。例如:

  1. /**//********** example 3 **********/   
  2.  
  3. set rowcount 0  
  4. select NULL mykey, * into #mytemp from authors  
  5.  
  6. set rowcount 1  
  7. update #mytemp set mykey = 
  8.  
  9. while @@rowcount > 0  
  10. begin  
  11.     set rowcount 0  
  12.     select * from #mytemp where mykey = 
  13.     delete #mytemp where mykey = 
  14.     set rowcount 1  
  15.     update #mytemp set mykey = 
  16. end  
  17. set rowcount 0  


免責聲明!

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



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