I have 2 tables "Vector" and "VectorElement". A vector has many elements so there is a foreign key relation between Vector and VectorElement with a cascaded delete.
Vector has a field VectorSize that contains the number the number of related records in VectorElement.
Obviously this field is redundant but it optimizes performance and keeps our queries simple as we are oftyen interested in the number of elements in a vector.
There is a trigger on VectorElement that updates the VectorSize field in Vector. This trigger works but gets very slow when many Vector records are deleted or inserted in one transaction.
When the Vectors get deleted, the cascaded delete deletes the VectorElements after which the trigger fires. Now the trigger does update the to-be-deleted Vector record which could cause some trouble but this also happens with inserts.
Here is the trigger:
CREATE TRIGGER [TFact].[AfterDeleteInsertVectorElement]
ON [TFact].[VectorElement]
AFTER DELETE, INSERT
AS
BEGIN
SET NOCOUNT ON;
WITH cteChangedVectors AS
(
SELECT DISTINCT i.VectorId
FROM inserted i
UNION
SELECT DISTINCT i.VectorId
FROM deleted i
)
UPDATE
TFact.Vector
SET
VectorSize = x.size
FROM
Vector v
JOIN
(SELECT VectorId, COUNT(*) as size FROM TFact.VectorElement GROUP BY VectorId) x
ON v.Id = x.VectorId
JOIN cteChangedVectors chg ON chg.VectorId = v.Id
END