Database reference - AdventureWorks

AdventureWorks -  triggers -  [Sales].[iStore]

Description

AFTER INSERT trigger inserting Store only if the Customer does not exist in the Individual table. 

Trigger properties

namevalue
parentStore
typeAfter Insert   
is first insertfalse
is last insertfalse
is first updatefalse
is last updatefalse
is last deletefalse
is first deletefalse
is disabledfalse
is not for replicationfalse

Dependency graph

uspLogErroruspPrintErrorIndividualStoreiStore

Objects that [Sales].[iStore] depends on

nameobject typelevel
uspLogErrorstored procedure1
uspPrintErrorstored procedure2
ErrorLogtable2
Individualtable1
Storetable1
Nametype2

Code

CREATE TRIGGER [Sales].[iStore] ON [Sales].[Store] 
AFTER INSERT AS 
BEGIN
    DECLARE @Count int;

    SET @Count = @@ROWCOUNT;
    IF @Count = 0 
        RETURN;

    SET NOCOUNT ON;

    BEGIN TRY
        -- Only allow the Customer to be a Store OR Individual
        IF EXISTS (SELECT * FROM inserted INNER JOIN [Sales].[Individual] 
            ON inserted.[CustomerID] = [Sales].[Individual].[CustomerID]) 
        BEGIN
            -- Rollback any active or uncommittable transactions
            IF @@TRANCOUNT > 0
            BEGIN
                ROLLBACK TRANSACTION;
            END
        END;
    END TRY
    BEGIN CATCH
        EXECUTE [dbo].[uspPrintError];

        -- Rollback any active or uncommittable transactions before
        -- inserting information in the ErrorLog
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END

        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;

Powered by Yoyodyne © 1971