@@TRANCOUNT (Transact-SQL)

适用于:SQL ServerAzure SQL 数据库Azure SQL 托管实例Azure Synapse AnalyticsAnalytics Platform System (PDW)Microsoft Fabric 中的仓库

返回在当前连接上执行的 BEGIN TRANSACTION 语句的数目。

Transact-SQL 语法约定

语法

@@TRANCOUNT  

注意

Azure Synapse Analytics 中的无服务器 SQL 池不支持此语法。

注意

若要查看 SQL Server 2014 (12.x) 及更早版本的 Transact-SQL 语法,请参阅早期版本文档

返回类型

integer

注解

BEGIN TRANSACTION 语句将 @@TRANCOUNT 增加 1。 ROLLBACK TRANSACTION 将 @@TRANCOUNT 递减到 0,但 ROLLBACK TRANSACTION savepoint_name 除外,它不影响 @@TRANCOUNT。 COMMIT TRANSACTION 或 COMMIT WORK 将 @@TRANCOUNT 递减 1。

示例

A. 演示 BEGIN 和 COMMIT 语句的效果

下面的示例演示嵌套的 BEGINCOMMIT 语句对 @@TRANCOUNT 变量产生的效果。

PRINT @@TRANCOUNT  
--  The BEGIN TRAN statement will increment the  
--  transaction count by 1.  
BEGIN TRAN  
    PRINT @@TRANCOUNT  
    BEGIN TRAN  
        PRINT @@TRANCOUNT  
--  The COMMIT statement will decrement the transaction count by 1.  
    COMMIT  
    PRINT @@TRANCOUNT  
COMMIT  
PRINT @@TRANCOUNT  
--Results  
--0  
--1  
--2  
--1  
--0  

B. 演示 BEGIN 和 ROLLBACK 语句的效果

下面的示例演示嵌套的 BEGIN TRANROLLBACK 语句对 @@TRANCOUNT 变量产生的效果。

PRINT @@TRANCOUNT  
--  The BEGIN TRAN statement will increment the  
--  transaction count by 1.  
BEGIN TRAN  
    PRINT @@TRANCOUNT  
    BEGIN TRAN  
        PRINT @@TRANCOUNT  
--  The ROLLBACK statement will clear the @@TRANCOUNT variable  
--  to 0 because all active transactions will be rolled back.  
ROLLBACK  
PRINT @@TRANCOUNT  
--Results  
--0  
--1  
--2  
--0  

另请参阅

BEGIN TRANSACTION (Transact-SQL)
COMMIT TRANSACTION (Transact-SQL)
ROLLBACK TRANSACTION (Transact-SQL)
系统函数 (Transact-SQL)