这里讲讲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).
参考官网: