我有以下触发器让我感到悲伤。
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
以上工作正常,但它使用我不想要的相同数据更新所有行。我只希望它从另一个名为baseEnd
的列
WHERE jm.jobmst_alias = 'blah' AND baseEnd <= i.jobrun_time AND JobRunID IS NOT NULL
这是我想象的应该工作,但事实并非如此。我做错了什么?
答案 0 :(得分:0)
查看代码中的表格
UPDATE [db2].[dbo].[table2]
SET
....
FROM inserted i
inner join jobmst jm on jm.jobmst_id = i.jobmst_id
where jm.jobmst_alias = 'blah'
如果您要更新其中的匹配记录,则不应该在FROM子句中使用table2。
否则你只是从inserted和jobmst表中获取一些记录,并从其中一个中激发值到table2中的所有记录
这就是为什么它无论如何都不起作用
很难看出你想要实现的逻辑是什么,但这可能是你需要的
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'