遇到一道面试题,要把1-1万个数分批10次提交全部插入表里面,当时都不理解什么是分批的要求。
先建个表
CREATE TABLE Customers3
(
CustomerID INT NOT NULL,
CustomerName CHAR(10) NOT NULL,
CustomerAddress CHAR(10) NOT NULL,
Comments CHAR(5) NOT NULL,
Value INT NOT NULL
)
GO
传统的插入数据,一般这样就可以了,不过要18秒
declare @begintime datetime
declare @endtime datetime
set @begintime=getdate()
DECLARE @i INT = 1
WHILE (@i <= 100000)
BEGIN
INSERT INTO Customers3 VALUES
(
@i,
'C1',
'C2',
'C3',
@i
)
SET @i += 1
END
set @endtime=getdate()
select @endtime,@begintime,@endtime-@begintime
GO
先插入在提交,
DECLARE @i INT = 1
declare @bian int =1000
declare @begintime datetime
declare @endtime datetime
set @begintime=getdate()
WHILE (@i <= 100000)
BEGIN
if(@i%@bian=0)
begin
if(@@trancount>0)
begin
commit tran
end
else
begin
begin tran
end
end
INSERT INTO Customers3 VALUES
(
@i,
'C1',
'C2',
'C3',
@i
)
SET @i += 1
END
if(@@trancount>0)
commit tran
set @endtime=getdate()
select @endtime,@begintime,@endtime-@begintime
GO
这样能够在10秒内插入,其实就是在原来的基础上加一个分组的值,先把组的语句统一再执行,就好比
第一种是循环的
begin tran
insert ***
commit tran
***
begin tran
insert ***
commit tran
第二种是嵌套再循环的
begin tran
insert ***
***
begin tran
insert***
commit tran*** commit tran
所以逻辑上就可以加快速度了