简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM