当从另一个相关 table 中删除重复行时,创建要从 table 中删除的触发器

Creating a Trigger to delete from table when deleting duplicate rows from another related table

我正在使用 sqlserver,当我从 Xtable 中删除重复行时,我创建了触发器以从 YTable 中删除。 注意:YTable 有一个来自 XTable 的外键 On_ID

触发查询

CREATE TRIGGER trgAfterDeletev4 ON XTable

 AFTER DELETE
 AS
 declare @empid int;

 select @empid=d.[On_ID] from deleted d; 

 Delete from YTable
 where [On_ID]= @empid
 PRINT 'AFTER DELETE TRIGGER fired.'

从 XTable 中删除重复行

WITH C AS(
   SELECT  *,
       RN = ROW_NUMBER()OVER(PARTITION BY [col1] ORDER BY [col2])
   FROM [Sourcing].[src].XTable
  )
  DELETE FROM C WHERE RN > 1

结果

(0 row(s) affected) AFTER DELETE TRIGGER fired.

(1271060 row(s) affected)

请问这些问题有什么问题

非常感谢

声明

select @empid=d.[On_ID] from deleted d
如果您要从 XTable 中删除多条记录,

将无法正常工作,因为您无法将多个 ID 放入单个整数变量中。

您只需将触发器中的删除语句更改为

 Delete from YTable
 where [On_ID] in (select [On_ID] from deleted)