原文來自: 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_m4.使用臨時變量來操作數據
5.整個循環結束後刪除臨時表