T-SQL 循环表的一种方式

原文来自: 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.整个循环结束后删除临时表

转载于:https://www.cnblogs.com/wcgsir/p/6181642.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值