包裹在显式事务中的SSMS中的T-SQL为什么运行得更快

Sum*_*ith 1 t-sql sql-server ssms transactions

该查询只是将相同的值“ hello”插入表中1000次。

当此查询在显式事务中运行时(在begin tran和中包装),commit tran它会立即运行。但是,如果begin tran & commit tran注释已被注释掉,则大约需要8秒钟才能完成!

谁能解释一下?

查看下面的查询和结果:

显式:

/*------------------------
drop table Test

create table Test (Name varchar(10))

begin tran
    set nocount on
    declare @i int = 1000

    select 'START: ', getdate() -- trick to get row title printed

    while (@i > 0)
    begin
        insert into Test (Name)
            select 'hello'
        set @i = @i - 1
    end

    select 'END: ', getdate() -- trick to get row title printed
    commit tran
------------------------*/

START:  2019-10-30 17:50:54.283  
END  :  2019-10-30 17:50:54.313  
Run Code Online (Sandbox Code Playgroud)

隐式:

/*------------------------
drop table Test

create table Test (Name varchar(10))

--begin tran
set nocount on
declare @i int = 1000

select 'START: ', getdate() -- trick to get row title printed

while (@i > 0)
begin
    insert into Test (Name)
        select 'hello'
    set @i = @i - 1
end

select 'END: ', getdate() -- trick to get row title printed
--commit tran
------------------------*/

START:  2019-10-30 17:51:48.203  
END  :  2019-10-30 17:51:56.520  
Run Code Online (Sandbox Code Playgroud)

编辑:在我的连接设置IMPLICIT_TRANSACTIONS = OFF。我上面所说的“隐式交易”只是缺少显式交易。

小智 6

提交事务后,SQL Server需要加强(写入磁盘或受电源保护的缓存)。一个使用隐式trx,由于循环,您有1000个trx,SQL需要为trx日志执行1000个ios。

将它们包装在一个trx中时,sql只需为trx日志执行几个ios(取决于trx日志缓冲区)。因此性能更好。

  • @Sumith就是这样工作的。循环中的每个插入都必须是单个ATOMic事务。为了使其工作,必须为每个插入使用事务。您的带有显式事务的代码在单个事务中执行1000次插入。 (3认同)
  • @Sumith,缺少隐式事务是自动提交的,意味着每个语句本身就是一个事务。这不同于隐式事务,后者启动一个事务(可以跨越多个语句),并且必须显式提交。 (2认同)