0

我现在一直在查找这个,我找不到在插入发生后但在提交发生之前触发触发器的任何方法。我需要这样做,以便在插入的信息有问题时能够恢复角色,但还需要检查插入的信息,因此需要在插入完成后进行。

是否有执行此操作的触发器或任何可以重现相同功能的方法?

4

2 回答 2

1

查看文档中关于 AFTER TRIGGER 的说明。

AFTER 指定仅当触发 SQL 语句中指定的所有操作都已成功执行时才触发 DML 触发器。

您可以轻松编写 AFTER 触发器,但不能使用它来控制事务提交之前发生的情况。可能有一个显式事务保持打开状态,直到例如“手动”回滚或提交。

于 2013-08-07T09:20:34.560 回答
1

触发器在提交发生之前被激活。ROLLBACK如果某些检查失败,您可以在触发器中使用:

CREATE TABLE dbo.Product(
    Id INT NOT NULL PRIMARY KEY,
    Name NVARCHAR(100) NOT NULL,
    UnitPrice NUMERIC(9,2) NOT NULL -- CHECK (UnitPrice > 0)
);
GO
CREATE TRIGGER trgIU_Product_VerifyUnitPrice
ON dbo.Product
AFTER INSERT, UPDATE
AS
BEGIN
    IF UPDATE(UnitPrice)
    BEGIN
        -- For simple checks you could use CHECK constraints
        -- inserted and deleted are virtual tables store the new and the old rows (values)
        IF EXISTS(SELECT * FROM inserted WHERE UnitPrice <= 0)
        BEGIN
            ROLLBACK; -- It "cancels" current transaction
            RAISERROR('Wrong UnitPrice.',16,1); -- It notifies the caller that there is an error
        END
    END
END;
GO

SET NOCOUNT ON;
PRINT 'Test #1';
INSERT INTO dbo.Product (Id,Name,UnitPrice)
SELECT  1 , 'PCs      ', 1200;

PRINT 'Test #2';
INSERT INTO dbo.Product (Id,Name,UnitPrice)
SELECT  2 , 'MACs     ', 2200;

PRINT 'Test #3';
INSERT INTO dbo.Product (Id,Name,UnitPrice)
SELECT  3 , 'Keyboard ', 0;

PRINT 'Test #4';
INSERT INTO dbo.Product (Id,Name,UnitPrice)
SELECT  4 , 'AAA', 111
UNION ALL
SELECT  5 , 'BBB', 0;
GO

PRINT 'Test #5';
BEGIN TRANSACTION;
INSERT INTO dbo.Product (Id,Name,UnitPrice)
SELECT  6 , 'CCC', 222
UNION ALL
SELECT  7 , 'DDD', 0;
COMMIT TRANSACTION;
GO
SELECT @@TRANCOUNT AS [Active transactions count];
GO

PRINT 'Test #6';
SELECT * FROM dbo.Product;

结果:

/*
Test #1

Test #2

Test #3
Msg 50000, Level 16, State 1, Procedure trgIU_Product_VerifyUnitPrice, Line 11
Wrong UnitPrice.
Msg 3609, Level 16, State 1, Line 11
The transaction ended in the trigger. The batch has been aborted.

Test #4
Msg 50000, Level 16, State 1, Procedure trgIU_Product_VerifyUnitPrice, Line 11
Wrong UnitPrice.
Msg 3609, Level 16, State 1, Line 2
The transaction ended in the trigger. The batch has been aborted.

Test #5
Msg 50000, Level 16, State 1, Procedure trgIU_Product_VerifyUnitPrice, Line 11
Wrong UnitPrice.
Msg 3609, Level 16, State 1, Line 3
The transaction ended in the trigger. The batch has been aborted.
Active transactions count
-------------------------
0

Test #6
Id Name UnitPrice
-- ---- ---------
1  PCs  1200.00
2  MACs 2200.00
*/

参考资料:http ://technet.microsoft.com/en-us/library/ms189799.aspx

于 2013-08-07T10:15:47.017 回答