XACT_STATE()

本文介绍SQL Server中如何使用XACT_STATE()函数来判断当前会话的事务状态,并通过示例展示了如何结合BEGIN TRY...BEGIN CATCH块进行错误处理,确保数据的一致性和事务的正确提交或回滚。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XACT_STATE() 1 -- commitable; 0 -- have no trasaction; -1 -- uncommitable

 

 

IF (XACT_STATE() = 1) AND (@itc = 0) COMMIT TRAN;

1 -- The session has an active transaction. The session can perform any actions, including writing data and committing the transaction.

 

 

0 -- There is no transaction active for the session.

-1 -- The session has an active transaction, but an error has occurred that has caused the transaction to be classified as an uncommittable transaction.

 

SAMPLE 1:

USE AdventureWorks;
GO

-- SET XACT_ABORT ON will render the transaction uncommittable
-- when the constraint violation occurs.
SET XACT_ABORT ON;

BEGIN TRY
    BEGIN TRANSACTION;
        -- A foreign key constraint exists on this table. This 
        -- statement will generate a constraint violation error.
        DELETE FROM Production.Product
            WHERE ProductID = 980;

    -- If the delete succeeds, commit the transaction. The CATCH
    -- block will not execute.
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    -- Test XACT_STATE for 0, 1, or -1.
    -- If 1, the transaction is committable.
    -- If -1, the transaction is uncommittable and should 
    --     be rolled back.
    -- XACT_STATE = 0 means there is no transaction and
    --     a COMMIT or ROLLBACK would generate an error.

    -- Test if the transaction is uncommittable.
    IF (XACT_STATE()) = -1
    BEGIN
        PRINT 'The transaction is in an uncommittable state.' +
              ' Rolling back transaction.'
        ROLLBACK TRANSACTION;
    END;

    -- Test if the transaction is active and valid.
    IF (XACT_STATE()) = 1
    BEGIN
        PRINT 'The transaction is committable.' + 
              ' Committing transaction.'
        COMMIT TRANSACTION;   
    END;
END CATCH;
GO
SAMPLE 2:
USE [CoreDB]
GO
/****** Object: StoredProcedure [FlexGoV25].[sp_AddConfig]    Script Date: 01/04/2008 12:38:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [FlexGoV25].[sp_AddConfig]
    @NameSpace nvarchar(50),
    @Name       nvarchar(50),
    @Value      nvarchar(256),
@Type       smallint
AS
    DECLARE
        @Return         int,
        @itc            int;             
  
    SELECT
        @Return = 1,
        @itc = @@TRANCOUNT;
           
    SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
      BEGIN TRY
        --The proc is not called by another transaction,begin transacton
        IF (@itc = 0) BEGIN TRANSACTION;
       
        BEGIN TRY
            INSERT INTO [FlexGoV25].[Configuration]
                (Type, NameSpace, Name, Value)
                VALUES (@Type, @NameSpace, @Name, @Value);
        END TRY
        BEGIN CATCH
              IF ERROR_NUMBER() = 2601  --unique index violation
            BEGIN
                --Namespace and Name exist, update the value
                UPDATE [FlexGoV25].[Configuration]
                    SET Value = @Value
                    WHERE Type = @Type AND NameSpace = @NameSpace AND Name = @Name;
            END
            ELSE
            BEGIN
                --Throw retry exception
                GOTO FAILED;
            END
        END CATCH
          SELECT @Return = 0;
COMMITTRAN:
        -- commit transaction if the proc begin the transaction and active
        IF (XACT_STATE() = 1) AND (@itc = 0) COMMIT TRAN;
        RETURN @Return
    END TRY
    BEGIN CATCH
        GOTO FAILED;
    END CATCH
FAILED:
        -- rollback if the transaction is active and start from the proc
        -- @itc is the the initial transaction count when it enters the proc,
        -- XACT_STATE() is zero when the transaction inactive
        IF (@itc = 0) AND (@@TRANCOUNT > 0) AND (XACT_STATE() <> 0) ROLLBACK TRAN;
USE [DXQcontrol_L1HIMCP1_Operational_W] GO /****** Object: StoredProcedure [dbo].[prodExecmgmtIdent__processBR] Script Date: 7/29/2025 9:03:21 AM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /*----------------------------------------------------------------------- Project: Duerr EcoEmos - Module Ident Stored Procedure: dbo.prodExecmgmtIdent__processBR Author: JM Initial date: 11. Nov 2020 Revisions: rev 1 - 11. Nov 2020, JM: wrapper function for the old OrderManagement to call dbo.prodExecmgmtIdent__processDR Input: @arg_dateEvt PLC timestamp of the reading event @arg_szRWStationTag Tagname for the reader (configured in table DS_CfgRegistrationPoint_TAB and for FB369 in addition in file IdentServer.ini) @arg_szDatasetIn Tracking data from PLC Output: @arg_szDatasetOut The mds data string which was merged by the new data from PLC and the last stored data string from DS_MDS_TAB Return: See the return codes of the several variables with name @iRetCode... ------------------------------------------------------------------------*/ CREATE PROCEDURE [dbo].[prodExecmgmtIdent__processBR] @arg_dateEvt DATETIME ,@arg_szRWStationTag NStringMin ,@arg_szDatasetIn VARCHAR(MAX) ,@arg_szDatasetOut VARCHAR(MAX) OUTPUT AS BEGIN SET NOCOUNT ON; SET XACT_ABORT ON; SET DEADLOCK_PRIORITY HIGH; DECLARE @object_name VARCHAR(128) = OBJECT_SCHEMA_NAME(@@PROCID) + '.' + OBJECT_NAME(@@PROCID); ---------------------------------------------------------------------------------------------------- -- PRREQ-1908: avoid start of process with an open or uncommitted transaction DECLARE @log VARCHAR(MAX) = ''; DECLARE @tempTable TABLE(logExt VARCHAR(MAX)); IF XACT_STATE() <> 0 BEGIN SET @log = 'Start ' + @object_name + '; '; SET @log += '@@TRANCOUNT = ' + CAST(@@TRANCOUNT AS VARCHAR(MAX)) + '; '; SET @log += 'XACT_STATE() = ' + CAST(XACT_STATE() AS VARCHAR(MAX)) + '; '; SET @log += '@@spid = ' + CAST(@@spid AS VARCHAR(MAX)) + '; '; SET @log += 'ProcParam: '; SET @log += 'rwStation: ' + @arg_szRWStationTag + '; '; SET @log += 'bodyId: ' + dbo.DS_FCT_GetPLCValueOf_(@arg_szDatasetIn, 'bodyId') + '; '; SET @log += 'skidId: ' + dbo.DS_FCT_GetPLCValueOf_(@arg_szDatasetIn, 'skidId') + '; '; SET @log += 'skidType: ' + dbo.DS_FCT_GetPLCValueOf_(@arg_szDatasetIn, 'skidType') + '; '; INSERT INTO @tempTable (logExt) SELECT DISTINCT 'spid=' + CAST(S.spid AS VARCHAR(MAX)) + '; hostname=' + RTRIM(S.hostname) + '; program_name=' + RTRIM(S.program_name) + '; hostprocess=' + RTRIM(S.hostprocess) + '; text=' + D.text + '; lastwaittype=' + RTRIM(S.lastwaittype) FROM sys.sysprocesses S CROSS APPLY sys.dm_exec_sql_text(S.sql_handle) D WHERE S.open_tran > 0; --ORDER BY S.hostname, S.program_name; ROLLBACK TRANSACTION; INSERT INTO dbo.DS_MDSErrorLog_TAB (dateEvt, rwStationId, source, errorCode, errorText) SELECT GETDATE(), @arg_szRWStationTag, @object_name, 'WARNING', isnull(logExt,'-') FROM @tempTable; EXEC dbo.DS_SP_MDSWriteToErrorLog @arg_rwStationId = @arg_szRWStationTag, @arg_szSource = @object_name, @arg_szErrorCode = 'WARNING', @arg_szErrorText = @log; END; ---------------------------------------------------------------------------------------------------- DECLARE @iRetValue INT; ------------------------------------------------------------------------------- -- write this information into log EXEC [dbo].[DS_SP_MDSWriteToLogger] @arg_szRWStationTag, @object_name, @arg_szDatasetIn; ------------------------------------------------------------------------------- -- set the prober function code SET @arg_szDatasetIn = STUFF( @arg_szDatasetIn, 1, 2, 'DR'); EXEC @iRetValue = [dbo].[prodExecmgmtIdent__processDR] @arg_dateEvt, -- DATETIME @arg_szRWStationTag, -- NStringMin @arg_szDatasetIn, -- VARCHAR(MAX) @arg_szDatasetOut OUTPUT; -- VARCHAR(MAX) RETURN @iRetValue; END; GO 详细解析此sqlserver的功能
07-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值