SQL插入100万个自然数

本文对比了不同方法在SQL Server中批量插入大量数据的性能,包括使用WITH语句生成序列和循环插入。测试结果显示,利用WITH语句进行一次性批量插入在有无索引的情况下均优于循环插入,并且在空表情况下性能提升显著。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL插入100万个自然数到表(id为主键)

方案一

with Result as(

select aaa.col*100000+ aa.col*10000+ a.col*1000+b.col*100+c.col*10+d.col+1 as col
from 
(select 0 as col union all select 1 union all select 2 union all 
select 3 union all select 4 union all select 5 union all 
select 6 union all select 7 union all select 8 union all select 9)aaa
cross join 
(select 0 as col union all select 1 union all select 2 union all 
select 3 union all select 4 union all select 5 union all 
select 6 union all select 7 union all select 8 union all select 9)aa
cross join 
(select 0 as col union all select 1 union all select 2 union all 
select 3 union all select 4 union all select 5 union all 
select 6 union all select 7 union all select 8 union all select 9)a
cross join 
(select 0 as col union all select 1 union all select 2 union all 
select 3 union all select 4 union all select 5 union all 
select 6 union all select 7 union all select 8 union all select 9)b
cross join 
(select 0 as col union all select 1 union all select 2 union all 
select 3 union all select 4 union all select 5 union all 
select 6 union all select 7 union all select 8 union all select 9)c
cross join 
(select 0 as col union all select 1 union all select 2 union all 
select 3 union all select 4 union all select 5 union all 
select 6 union all select 7 union all select 8 union all select 9)d

)
insert into normaltable([id]) select * from Result order by col

准备工作

设置数据库大小为50MB,日志文件初始大小为600MB,增长为500MB,使得插入过程中硬盘文件空间全部预备好。每次测试均收缩日志文件到600MB。

有索引无索引内存表有索引
(经测在非性能的某些方面是个坑,
暂时不要使用内存表)
100万2秒3秒(delete 1秒)
10万

(100万个)MSSQL2014 普通表83秒(12048/s),普通表无索引首次2秒13秒(76923/s),内存表4秒(25万个/s)
(10万个)MSSQL2014 普通表秒(/s),普通表无索引秒(/s ~/s),内存表1秒(万个/s)
作为参考一般应用程序单线程发送请求“select 1”能达到每秒8000~12000的水平
(上面产生数据的临时结果集代码是从csdn里翻出来的不是原创)


方案二(仅插入10万个)

begin tran

DECLARE @id int
SET @id = 1
while @id <= 100000 begin
insert into dbo.memorytable ([id]) values(@id)
SET @id = @id + 1
end
commit tran;

(10万个)普通表(首次运行在空表上43秒)24秒(2326/s)普通表不含主键、索引8秒(12500/s) 内存表4秒(25000/s)
(20万个)普通表秒(/s)普通表不含主键、索引秒(/s) 内存表11秒(/s)
(40万个)普通表秒(/s)普通表不含主键、索引秒(/s) 内存表21秒(/s)

结论

空表插入时,无索引性能高很多
批量从数据源插入比循环插入快
(SQL脚本中循环比应用程序中循环快)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值