SQL触发器删除最旧的重复项

时间:2014-09-19 13:38:56

标签: sql sql-server triggers

我有以下表格

HOLIDAY_DATE_TABLE:

USE BillingUI;
CREATE TABLE HOLIDAY_DATE_TABLE
(
HID INT IDENTITY PRIMARY KEY,
TABLE_NUMBER nchar(2) NOT NULL,
HOLIDAY_DATE nchar(8) NOT NULL,
FIELD_DESCRIPTION nVARchar(43) NULL,
);

tbl8_update_transactions:

USE BillingUI;
CREATE TABLE tbl8_update_transactions
(
TID INT IDENTITY PRIMARY KEY,
TABLE_NUMBER nchar(2) NOT NULL,
HOLIDAY_DATE nchar(8) NOT NULL,
FIELD_DESCRIPTION nVARchar(43) NULL,
HID int,
FOREIGN KEY (HID) REFERENCES HOLIDAY_DATE_TABLE (HID)
);

我正在尝试为tbl8_update_transactions写一个触发器。它的目标是识别具有重复外键值的记录,并删除该行的所有实例(最新的除外)(可通过具有最高主键号识别,因为它是auto_incrementing)。

到目前为止我所拥有的是......

CREATE TRIGGER tbl8_cleanup
ON tbl8_update_transactions
FOR INSERT
AS
BEGIN
SELECT HID, COUNT(*)
FROM tbl8_update_transactions
GROUP BY HID
HAVING COUNT(*) > 1;
DELETE FROM tbl8_update_transactions
WHERE COUNT(HID) > 1;
END; 

我不确定如何使用触发器删除具有重复项的行的所有实例,但具有最高主键编号(TID)的实例除外。

2 个答案:

答案 0 :(得分:3)

我会在CTE中使用row_number()

with todelete as (
      select t.*, row_number() over (partition by HID order by TID desc) as seqnum
      from tbl8_update_transactions t
     )
delete from todelete
    where seqnum > 1;

答案 1 :(得分:1)

不是每次发生任何活动时扫描整个表格,为什么不进行更多目标:

CREATE TRIGGER tbl8_cleanup
ON tbl8_update_transactions
INSTEAD OF INSERT --<-- Act before the new rows have been inserted
AS
BEGIN
DELETE FROM tbl8_update_transactions where HID in (select HID from inserted)
INSERT INTO tbl8_update_transactions (/* column list */)
SELECT /* column list */ from inserted
END; 

因此,在我们插入任何新行之前,我们首先删除重复的任何行,然后执行我们被要求执行的实际插入。


作为一般规则,如果您的触发器代码未引用inserted和/或deleted,则可能已损坏。有关详细信息,请参阅documentation