Kairan
Kairan

Reputation: 5542

SQL Server Trigger On Update or Insert

Here is my tables:

Report Table:

ReportID    Status
1           'out'
2           null

Log Table

LogID       Status      ReportID
1           'out'       1

When I insert a new record into Log table I want a trigger to update the corresponding status field. Example: Insert to log (LogID=2, Status='out', ReportID=2) I would want to update the report table for the matching ReportID(2) fild for Status so they match.

The output would end up like this; Report Table:

ReportID    Status
1           'out'
2           'out'     //changed from null to out by the Log trigger

Log Table

LogID       Status      ReportID
1           'out'       1
2           'out'       2

The question here is how do I create a Trigger to update the second table when the first one either has a new insert, or an update to an existing record?

Upvotes: 1

Views: 3034

Answers (1)

sgeddes
sgeddes

Reputation: 62861

I think you might be looking for something like this:

create trigger updatereport on log 
after insert, update
as
update r
set status = i.status
from report r 
  inner join inserted i on r.reportid = i.reportid;

SQL Fiddle Demo

Upvotes: 3

Related Questions