@@TRANCOUNT (Transact-SQL)

傳回已經針對目前連接進行的 BEGIN TRANSACTION 陳述式數目。

主題連結圖示Transact-SQL 語法慣例

語法

@@TRANCOUNT

傳回類型

integer

備註

BEGIN TRANSACTION 陳述式會遞增 @@TRANCOUNT,遞增量為 1。ROLLBACK TRANSACTION 會將 @@TRANCOUNT 遞減到 0,不過 ROLLBACK TRANSACTION savepoint_name 除外,它不會影響 @@TRANCOUNT。COMMIT TRANSACTION 或 COMMIT WORK 會遞減 @@TRANCOUNT,遞減量為 1。

範例

A. 顯示 BEGIN 和 COMMIT 陳述式的作用

下列範例會顯示巢狀 BEGIN 和 COMMIT 陳述式對 @@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 TRAN 和 ROLLBACK 陳述式對 @@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