Transact-SQL語句遍歷結(jié)果集的三種方法
Transact-SQL語句是可以實(shí)現(xiàn)遍歷的,有三種方法使用可以通過使用Transact-SQL語句遍歷一個(gè)結(jié)果集。下面就為您詳細(xì)介紹Transact-SQL語句遍歷結(jié)果集的幾種方法,供您參考。
一種方法是使用temp表。使用這種方法您創(chuàng)建的初始的SELECT語句的"快照"并將其用作基礎(chǔ)"指針"。例如:
- /**//********** 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
第二個(gè)的方法是表格的一行"遍歷"每次使用 Min 函數(shù)。此方法捕獲添加存儲(chǔ)的過程開始執(zhí)行之后, 假設(shè)新行必須大于當(dāng)前正在處理在查詢中的行的***標(biāo)識(shí)符的新行。例如:
- /**//********** 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
注意 : 兩個(gè)示例1和2,則假定源表中的每個(gè)行***的標(biāo)識(shí)符存在。在某些情況下,可能存在沒有***標(biāo)識(shí)符 如果是這種情況,您可以修改temp表方法使用新創(chuàng)建的鍵列。例如:
- /**//********** 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
【編輯推薦】
動(dòng)態(tài)sql中使用臨時(shí)表的實(shí)例