- --表变量1
- declare @tempTb Table(ID int, Name nvarchar(64))
- --表变量2
- declare @DtTb Table(ID int, Name nvarchar(64))
- insert into @DtTb select top 100 ID,Name from [dbo].[Students]
- --声明循环的变量
- declare @ID int;
- --通过ID循环
- while exists(select ID from @DtTb)
- begin
- set rowcount 1; --对整个会话取数据有效,即若以下有查询语句,也是限定只取一条
- --select top 1 @ID = ID from @DtTb; --用 top 1 只对此句查询有效
- select @ID = ID from @DtTb;
- --具体遍历业务
- insert into @tempTb select * from @DtTb where ID=@ID;
- set rowcount 0; --取消限定
- --遍历完一条一定要删掉此条,否则死循环!
- delete from @DtTb where ID=@ID;
- end
- select * from @tempTb;
delete from @tempTb;
- --临时表1
- create Table #tempTb(ID int, Dbo nvarchar(64))
- --临时表2
- create Table #DtTb(ID int, Dbo nvarchar(64))
- insert into #DtTb select top 100 ID,Dbo from [AnyImageGuLou02].[grid].[BHosCheckES]
- --声明循环的变量
- declare @ID int;
- --通过ID循环
- while exists(select ID from #DtTb)
- begin
- --set rowcount 1; --对整个会话取数据有效,即若以下有查询语句,也是限定只取一条
- select top 1 @ID = ID from #DtTb; --用 top 1 只对此句查询有效
- --select @ID = ID from #DtTb;
- --具体遍历业务
- insert into #tempTb select * from #DtTb where ID=@ID;
- --set rowcount 0; --取消限定
- --遍历完一条一定要删掉此条,否则死循环!
- delete from #DtTb where ID=@ID;
- end
- select * from #tempTb;
- --select * from #DtTb;
- --用完记得删掉临时表!
- drop table #tempTb;
- drop table #DtTb;