EXECUTE之后的事务计数表示BEGIN和COMMIT语句的数量不匹配。先前的计数= 1,当前计数= 2

时间:2016-04-01 13:11:43

标签: sql-server tsql triggers

我写了这个触发器:

ALTER TRIGGER [dbo].[trg_abort_insert]
ON [dbo].[F_DOCCURRENTPIECE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRY
    BEGIN TRAN

IF EXISTS (SELECT * 
           FROM Inserted i  
           INNER JOIN Deleted d ON i.CBMARQ= d.CBMARQ
           WHERE i.DC_Piece <> d.DC_Piece 
             AND i.DC_Domaine = 0

            AND i.DC_IdCol = 6)
COMMIT TRAN
END TRY
BEGIN CATCH  
SELECT ERROR_MESSAGE()
IF @@TRANCOUNT>0
        ROLLBACK
END CATCH;
END

我有这个错误: EXECUTE之后的事务计数表示BEGIN和COMMIT语句的数量不匹配。先前的计数= 1,当前计数= 2

Pleaze帮帮我

1 个答案:

答案 0 :(得分:2)

这是因为您有嵌套事务。我的意思是触发器触发时事务处于打开状态。您需要修改触发器来处理嵌套事务,如下所述:

create TRIGGER [dbo].[trg_abort_insert]
ON [dbo].[F_DOCCURRENTPIECE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
SET XACT_ABORT ON
declare @trancount int = @@trancount

BEGIN TRY
    if @trancount > 0
        begin
            save transaction t1
        end
    else
        begin
            begin transaction
        end

IF EXISTS (SELECT * 
           FROM Inserted i  
           INNER JOIN Deleted d ON i.CBMARQ= d.CBMARQ
           WHERE i.DC_Piece <> d.DC_Piece 
             AND i.DC_Domaine = 0

            AND i.DC_IdCol = 6)

    if @trancount = 0
        begin           
            COMMIT TRAN
        end
END TRY
BEGIN CATCH 

    if @trancount > 0
        rollback transaction t1
    if @trancount = 0
        rollback transaction
    SELECT ERROR_MESSAGE()

END CATCH;

这对你有用。如果这有帮助,请告诉我。