This trigger backs up data from dbo.node to dbo.nodearchive. While backups are important, I only need to do this once per day. Note that there is a field called dbo.NodeArchive.versionDate (smalldDatetime).
CREATE TRIGGER [dbo].[Node_update]
ON [dbo].[Node]
for UPDATE
AS
BEGIN
INSERT INTO dbo.NodeArchive ([NodeID]
,[ParentNodeID]
,[Slug]
,[xmlTitle]
...
,[ModifyBy]
,[ModifyDate]
,[CreateBy]
,[CreateDate])
SELECT [deleted].[NodeID]
,[deleted].[ParentNodeID]
,[deleted].[Slug]
,[deleted].[xmlTitle]
...
,[deleted].[ModifyBy]
,[deleted].[ModifyDate]
,[deleted].[CreateBy]
,[deleted].[CreateDate]
FROM [deleted] LEFT JOIN dbo.Node
ON [deleted].NodeID = dbo.Node.NodeID
WHERE deleted.ModifyDate <> dbo.Node.ModifyDate
END
GO
I am looking to backup changes, but never more than one backup version per day. If there is no change, there is no backup.
That’s not a trigger anymore – that’ll be a scheduled job. Triggers by their very definition execute whenever a given operation (
INSERT, DELETE, UPDATE) happens.Use the SQL Server Agent facility to schedule that T-SQL code to run once per day.
Read all about SQL Server Agent Jobs in the SQL Server Books Online on MSDN
Update: so if I understand correctly: you want to have an
UPDATEtrigger – but that trigger would only record theNodeIDthat were affected, into a “these nodes need to be backed up at night” sort of table. Then, at night, you would have a SQL Agent Job that runs and that scans that “work table” and for allNodeIDvalues stored in there, it would then execute that T-SQL statement to copy their data into theNodeArchivetable.With this approach, if your nodes with
NodeID = 42changes ten times, you’ll still only have a single entryNodeID = 42in your work table, and the nightly backup job would then copy that node only once into theNodeArchive.With this approach, you can decouple the actual copying (which might take time) from the update process. The
UPDATEtrigger only records whichNodeIDrows need processing – the actual processing then happens sometime later, at an off-peak hour, without disturbing users of your system.