AFTER INSERT, UPDATE trigger inserting Individual only if the Customer does not exist in the Store table and setting the ModifiedDate column in the Individual table to the current date.
Properties
Creation Date
08/01/2010 08:41
Encrypted
Ansi Nulls
Trigger Type
Insert
Delete
Update
After
Instead Of
Trigger Definition
CREATETRIGGER[Sales].[iuIndividual]ON[Sales].[Individual]
AFTER INSERT, UPDATENOTFORREPLICATIONASBEGINDECLARE@Countint;
SET@Count=@@ROWCOUNT;
IF@Count=0RETURN;
SET NOCOUNT ON;
IFEXISTS (SELECT*FROM inserted INNERJOIN[Sales].[Store]ON inserted.[CustomerID]=[Sales].[Store].[CustomerID])
BEGINIF@@TRANCOUNT>0BEGINROLLBACKTRANSACTION;
ENDEND;
IFUPDATE([CustomerID]) ORUPDATE([Demographics])
BEGINUPDATE[Sales].[Individual]SET[Sales].[Individual].[Demographics]= N'<IndividualSurvey xmlns="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey">
<TotalPurchaseYTD>0.00</TotalPurchaseYTD>
</IndividualSurvey>'FROM inserted
WHERE[Sales].[Individual].[CustomerID]= inserted.[CustomerID]AND inserted.[Demographics]ISNULL;
UPDATE[Sales].[Individual]SET[Demographics].modify(N'declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey";
insert <TotalPurchaseYTD>0.00</TotalPurchaseYTD>
as first
into (/IndividualSurvey)[1]')
FROM inserted
WHERE[Sales].[Individual].[CustomerID]= inserted.[CustomerID]AND inserted.[Demographics]ISNOTNULLAND inserted.[Demographics].exist(N'declare default element namespace
"http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/IndividualSurvey";
/IndividualSurvey/TotalPurchaseYTD') <>1;
END;
END;