Transact-SQL語句是可以實現遍歷的,有三種方法使用可以通過使用Transact-SQL語句遍歷一個結果集。下面就為您詳細介紹Transact-SQL語句遍歷結果集的幾種方法,供您參考。
一種方法是使用temp表。使用這種方法您創建的初始的SELECT語句的"快照"並將其用作基礎"指針"。例如:
- /**//********** example 1 **********/
- declare @au_id char( 11 )
- set rowcount 0
- select * into #mytemp from authors
- set rowcount 1
- select @au_idau_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_idau_id = au_id from #mytemp<BR/>
- end
- set rowcount 0
第二個的方法是表格的一行"遍歷"每次使用 Min 函數。此方法捕獲添加存儲的過程開始執行之后, 假設新行必須大於當前正在處理在查詢中的行的唯一標識符的新行。例如:
- /**//********** example 2 **********/
- declare @au_id char( 11 )
- 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