?
Solved

Help with Update Trigger

Posted on 2011-05-02
2
Medium Priority
?
201 Views
Last Modified: 2012-05-11
I have a table with four columns a CampaignRecipientID column,CampaignRecipientKey column,datetime created column and a datetime updated column.  I want to store a count which gets incremented by 1 whenever the DateTime field is updated. Ideally I would like to store this information in a separate database in a table with the following columns
CampaignRecipientID
CampaignRecipientKey
UpdatedCount
Is it possible to write a trigger to achieve this ? And if so how ?

Thanks,
Aditya
0
Comment
Question by:pmac38CDS
2 Comments
 
LVL 18

Accepted Solution

by:
lludden earned 1000 total points
ID: 35505004
Rather than log the updated count, just log each update, then you can query the log table to get the counts at any given time.  This will log the values after the change.

CREATE TRIGGER LogChanges ON mytable
FOR INSERT, UPDATE
AS
SET NOCOUNT ON

IF Update(Updated)
    INSERT INTO MyLogTable (CampaignRecipientID, CampaignRecipientKey, ChangeDate, ChangedBy)
      SELECT CampaignRecipientID, CampaignRecipientKey, getdate(), suser_sname()
      FROM inserted
0
 
LVL 9

Assisted Solution

by:kaminda
kaminda earned 1000 total points
ID: 35505021
Yes you can write a update trigger on your table. Code would be something like this
CREATE TRIGGER YourTriggerName
ON YourTableName AFTER UPDATE
AS
IF UPDATE(datetimeupdated)
BEGIN

UPDATE yourdatabase.dbo.yourdestinationtable 
SET UpdatedCount = UpdatedCount + 1
WHERE
tablekey = inserted.keycoulumn

RETURN
END

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question