简体   繁体   English

SQL Server:如果不存在则触发更新

[英]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 我只希望它更新从另一列称为baseEnd的插入时间之前的时间所在的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. 如果要更新匹配的记录,则FROM子句中不应该包含table2。

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 否则,您只是从插入表和Jobmst表中取回一些记录,并将其中之一的值激发到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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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