SQL Server:Post Insert Pre Commit Trigger

时间:2013-08-07 08:58:23

标签: sql-server database triggers

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

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

2 个答案:

答案 0 :(得分:1)

了解documentation关于AFTER TRIGGER的内容。

  

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

您可以轻松编写AFTER触发器,但不能使用它来控制事务提交之前发生的事情。可能有明确的交易保持开放,直到例如“手动”回滚或提交。

答案 1 :(得分: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