简体   繁体   中英

SQL Server : trigger update if not exists

I have the following trigger is causing me grief.

ALTER TRIGGER [dbo].[T_DMS_Factory_I]
   ON  [dbo].[jobrun]
   AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    IF NOT EXISTS (select * from inserted i
                   inner join [db2].[dbo].[table2] t2 on t2.JobRunID = i.jobrun_id)
       UPDATE [db2].[dbo].[table2]
       SET ProdDt = i.jobrun_proddt,
           CreateDt = GETDATE(),
           JobrunID = i.jobrun_id,
           Start = i.jobrun_time,
           End = i.jobrun_stachgtm,
           Status = i.jobrun_status,
           ActiveDuration = i.jobrun_duration,
           TotalDuration = i.jobrun_duration
       FROM inserted i
       INNER JOIN jobmst jm ON jm.jobmst_id = i.jobmst_id
       WHERE jm.jobmst_alias = 'blah'
END

The above works fine but it updates ALL the rows with the same data which I don't want. I only want it to update the row where the time is after before the time of the insert from another column called baseEnd

WHERE jm.jobmst_alias = 'blah' AND baseEnd <= i.jobrun_time AND JobRunID IS NOT NULL

That is what I'd imagine should work but it isn't. What am I doing wrong?

Looking at the tables in your code

UPDATE [db2].[dbo].[table2]
SET 
....
FROM inserted i
inner join jobmst jm on jm.jobmst_id = i.jobmst_id
where jm.jobmst_alias = 'blah'

shouldn't you have table2 in the FROM Clause if you're going to update matching records in it.

Otherwise you're just getting some records back from the inserted and jobmst tables and firing values from one of them into all the records in table2

That's why it's not working anyway

It's difficult to see quite what the logic you're trying to implement is but this might be what you need

UPDATE t2
SET ProdDt = i.jobrun_proddt,
CreateDt = GETDATE(),
JobrunID = i.jobrun_id,
Start = i.jobrun_time,
End = i.jobrun_stachgtm,
Status = i.jobrun_status,
ActiveDuration = i.jobrun_duration,
TotalDuration = i.jobrun_duration
FROM inserted i
inner join jobmst jm on jm.jobmst_id = i.jobmst_id
inner join [db2].[dbo].[table2] t2 ON  t2.baseEnd <= i.jobrun_time 
where jm.jobmst_alias = 'blah'

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