Wednesday, 7 December 2011

Umbraco table trigger to update a non-Umbraco table

Due to the way our system is setup I had to write a database trigger to monitor move and sort changes and log those changes into a non-Umbraco table with the node ID and a date. Below is the trigger I created:

USE (yourumbracodatabase)
GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TR_CNI_UmbracoNode_AfterUpdate]'))
DROP TRIGGER [dbo].[TR_CNI_UmbracoNode_AfterUpdate]
GO

/*
There are two very special tables that can exist only within triggers: the inserted and deleted tables. These tables are 
used to store the before and after state of the table that was affected by the INSERT, UPDATE, or DELETE statement that 
caused the trigger to fire in the first place. 
*/

CREATE TRIGGER TR_CNI_UmbracoNode_AfterUpdate ON dbo.umbracoNode AFTER UPDATE
AS
 DECLARE @id INT 
 
 CREATE TABLE #NodeIds
 (
  nodeId INT
 ) 
  
 IF UPDATE(parentID) OR UPDATE(sortOrder)
 BEGIN 
   
  SELECT  @id = d.id
  FROM  inserted i
  INNER JOIN deleted d ON i.id = d.id
  WHERE  d.parentID <> i.parentID
  OR   d.sortOrder <> i.sortOrder
  
  IF (@id IS NOT NULL)
  BEGIN     
   INSERT INTO #NodeIds
   SELECT @id -- Parent
   UNION ALL
   SELECT un.id -- Children
   FROM dbo.umbracoNode un
   WHERE un.[path] LIKE '%,' + CONVERT(NVARCHAR(40), @id) + ',%'   
  END
 END 
 
 -- Delete existing nodeId rows
 DELETE FROM dbo.T_CNI_PublishNodeData
 WHERE nodeId IN
 (
  SELECT nodeId
  FROM #NodeIds
 )

 -- Insert new dates for nodeIds   
 INSERT INTO dbo.T_CNI_PublishNodeData (nodeId, publishedDate)
 SELECT nodeId,
   GETUTCDATE()
 FROM #NodeIds

 DROP TABLE #NodeIds

No comments: