1、sql脚本使用表变量遍历数据示例:

--表变量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;

 

2、sql脚本使用临时表遍历数据示例:

--临时表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;

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/seanyan/p/13824732.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!