James A Mohler
James A Mohler

Reputation: 11120

Trigger that only runs runs once per day

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.

Upvotes: 3

Views: 2805

Answers (1)

marc_s
marc_s

Reputation: 754598

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 UPDATE trigger - but that trigger would only record the NodeID that 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 all NodeID values stored in there, it would then execute that T-SQL statement to copy their data into the NodeArchive table.

With this approach, if your nodes with NodeID = 42 changes ten times, you'll still only have a single entry NodeID = 42 in your work table, and the nightly backup job would then copy that node only once into the NodeArchive.

With this approach, you can decouple the actual copying (which might take time) from the update process. The UPDATE trigger only records which NodeID rows need processing - the actual processing then happens sometime later, at an off-peak hour, without disturbing users of your system.

Upvotes: 4

Related Questions