首页 > 数据库技术 > 详细

T-SQL 循环表的一种方式

时间:2016-12-15 01:07:25      阅读:198      评论:0      收藏:0      [点我收藏+]

原文来自: https://www.lesg.cn/netdaima/sqlservert-sql/2016-463.html

SsqlServer 中循环表有几种方式

1.临时表

2.游标

3….

下面就来说说怎么用临时表格来循环数据

create table t(
 
id int not null primary key identity(1,1),
 
dt datetime not null default(getdate()),
 
name varchar(100) not null default(‘‘)
 
)
--测试案例,给表插入数据
declare @count int ;set @count=0;
while(@count<100)
begin
set @count= @count+1
insert into t (name) values (NEWID())
end
select * from t
--判断临时表是否存在 如果存在则删除临时表
if exists(select 1 from tempdb..sysobjects where id=object_id(tempdb..#t_m))
begin
 drop table #t_m --删除临时表
end
--将数据插入临时表
select * into #t_m from t 
--开始循环表数据
 
 declare @tmid int ; -- 创建一个临时变量
While (exists ( select 1 from #t_m))
BEGIN
select top 1 @tmid =id from #t_m --拿出一条数据复制在临时变量里面, 用于待会删除该数据使用
--
 /*
 好了 在这里使用 @tmid 来操作 该条数据吧
 lesg.cn
 */
--
DELETE #t_m WHERE ID=@tmid; --删除一条临时表的数据
END
if exists(select 1 from tempdb..sysobjects where id=object_id(tempdb..#t_m))
begin
 drop table #t_m --操作结束后删除临时表
end

思路如下;
1.创建临时表格
2.while 循环临时表; 循环条件是 临时表是否存在
3. 获取一条临时表的数据; 记得使用top 1 否则数据一多起来性能低到你发疯 获得临时变量,临时变量等于该条数据的ID

select  top 1 @tmid =id from #t_m

4.使用临时变量来操作数据
5.整个循环结束后删除临时表

T-SQL 循环表的一种方式

原文:http://www.cnblogs.com/wcgsir/p/6181642.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!