隐式事务

这里讲讲SqlServer的隐式事务。(英文Implicit:含蓄的;暗示的;盲从的;)

隐式事务无需显示开始:不用 Begin Transaction,必须显示结束:以 Commit Transaction 或者 Rollback Transaction 方式结束。

语句迭代迭代:SET IMPLICIT_TRANSACTIONS { ON | OFF }

开了隐式事务后,下面的语句的语句就会自动开启隐式事务。

使用

要想知道当前有多少事务没有结束:@@TranCount

举例1:设置隐式事务关闭,虽然默认是关的。剩下多少事务没有结束。

--创建一个表
go  
IF (OBJECT_ID(N'dbo.t1',N'U') IS NOT NULL) DROP TABLE dbo.t1;  
go  
CREATE table dbo.t1 (a int);  
go  

--设置隐式事务为关闭,其实默认就是关的.
SET IMPLICIT_TRANSACTIONS OFF; 

--插入两条数据
INSERT INTO dbo.t1 VALUES (11);  
INSERT INTO dbo.t1 VALUES (12);  

--查看有多少条事务没有结束
PRINT N' @@TranCount, after INSERTs, == ' + CAST(@@TRANCOUNT AS NVARCHAR(10));  


--结果 @@TranCount, after INSERTs, == 0

如果不开启隐式事务,事务结束都是自动的。除非用 Begin Transaction。

--设置隐式事务为关闭,其实默认就是关的.
SET IMPLICIT_TRANSACTIONS OFF; 

--开始事务
BEGIN TRANSACTION; 
--插入两条数据
INSERT INTO dbo.t1 VALUES (11);  
INSERT INTO dbo.t1 VALUES (12);  
--查看有多少条数据没有关闭
PRINT N'@@TranCount, after INSERTs, == ' + CAST(@@TRANCOUNT AS NVARCHAR(10)); 

--结果 @@TranCount, after INSERTs, == 1

--结束事务
COMMIT TRANSACTION;
--查看有多少条数据没有关闭
PRINT N' @@TranCount, after INSERTs, == ' + CAST(@@TRANCOUNT AS NVARCHAR(10));  

--结果 @@TranCount, after INSERTs, == 0 

 

举例2:

--设置隐式事务开启
SET IMPLICIT_TRANSACTIONS ON;  
--插入两条 删除一条
INSERT INTO dbo.t1 VALUES (21); 
INSERT INTO dbo.t1 VALUES (22); 
delete from dbo.t1
PRINT N'[B.03] @@TranCount, after INSERTs, == ' + CAST(@@TRANCOUNT AS NVARCHAR(10));  
--提交一个事务
COMMIT TRANSACTION;  
PRINT N'[B.04] @@TranCount, after COMMIT, == ' + CAST(@@TRANCOUNT AS NVARCHAR(10));  
go  

--结果 
--[B.03] @@TranCount, after INSERTs, == 1
--[B.04] @@TranCount, after COMMIT, == 0

 

SET IMPLICIT_TRANSACTIONS ON;  
go  
--开启事务
BEGIN TRANSACTION;  
--进行添加 删除操作
INSERT INTO dbo.t1 VALUES (31);  
INSERT INTO dbo.t1 VALUES (32);  
delete from dbo.t1
PRINT N'[C.03] @@TranCount, after INSERTs, == ' + CAST(@@TRANCOUNT AS NVARCHAR(10));  
go  
--提交事务
COMMIT TRANSACTION;  
PRINT N'[C.04] @@TranCount, after a COMMIT, == ' + CAST(@@TRANCOUNT AS NVARCHAR(10));  
--提交事务
COMMIT TRANSACTION;  
PRINT N'[C.05] @@TranCount, after another COMMIT, == ' + CAST(@@TRANCOUNT AS NVARCHAR(10));  
go  

--[C.03] @@TranCount, after INSERTs, == 2
--[C.04] @@TranCount, after a COMMIT, == 1
--[C.05] @@TranCount, after another COMMIT, == 0

 

 

隐式事务不怎么用,除非 SET ANSI_DEFAULTS (Transact-SQL).

参考官网:https://docs.microsoft.com/en-us/sql/t-sql/statements/set-implicit-transactions-transact-sql?view=sql-server-2017

posted @ 2018-08-20 12:51  舒碧  阅读(637)  评论(0编辑  收藏  举报