不用游標也能遍歷記錄的sql語句例項

2021-06-23 02:22:37 字數 2393 閱讀 2504

--宣告變數表@tb

declare @tb table(id int,name varchar(50))

--新增測試資料

insert into @tb

select  6,'aa' union all

select  7,'bb' union all

select  8,'cc' union all

select  9,'dd' union all

select  10,'abc' union all

select  11,'ddef' union all

select  12,'fda' union all

select  13,'rewr' union all

select  14,'eyt' union all

select  15,'jjy' union all

select  16,'bbbxd' union all

select  17,'***' union all

select  18,'ffff' union all

select  19,'wwwwwwww' union all

select  20,'aaaaaaaaaa' 

/*檢視表中資料

select * from @tb 

*/--宣告迴圈用的「指標」

declare @min varchar(5)

--賦初值

select  @min=min(id) from @tb  

--開始迴圈

while @min is not null

begin

print @min  --列印當前「指標」的值

select  @min=min(id) from @tb where id>@min  --更新「指標」內容,使之移到下一記錄

enddeclare @temp table   

(   

[id] int identity(1,1),   

[name] varchar(10)   

)   

declare @tempid int,@tempname varchar(10)   

insert into @temp values('a')   

insert into @temp values('b')   

insert into @temp values('c')   

insert into @temp values('d')   

insert into @temp values('e')   

--select * from @temp   

while exists(select [id] from @temp)   

begin   

set rowcount 1    

select @tempid = [id],@tempname=[name] from @temp   

set rowcount 0   

delete from @temp where [id] = @tempid   

print 'name:----'+@tempname   

end  

--定義表變數

declare @temp table

([id] int identity(1, 1) ,

[name] varchar(10)

) declare @tempid int ,

@tempname varchar(10)

declare test_cursor cursor local for

select [id],[name] from @temp

--插入資料值

insert into @temp

values ( 'a' )

insert into @temp

values ( 'b' )

insert into @temp

values ( 'c' )

insert into @temp

values ( 'd' )

insert into @temp

values ( 'e' )

--開啟游標

open test_cursor

while @@fetch_status = 0

begin

fetch next from test_cursor into @tempid,@tempname

print 'name:----' + @tempname

end

close test_cursor

deallocate test_cursor

不用游標 遍歷記錄的sql語句

宣告變數表 tb declare tbtable id int,name varchar 50 新增測試資料 insert into tbselect6,aa union allselect7,bb union allselect8,cc union allselect9,dd union alls...

TSQL 不用游標的迴圈方法

方法一 select into t1 from dbo.horsebase declare id int declare t2 table id int while exists select horsenumber from t1 begin select top 1 id horsenumber...

TSQL 不用游標的迴圈方法

方法一 select into t1 from dbo.horsebase declare id int declare t2 table id int while exists select horsenumber from t1 begin select top 1 id horsenumber...