插入后如何查找重复值并删除它们(使用触发器)?

fas*_*ast 0 sql sql-server triggers duplicates sql-delete

我该如何编写触发器来查找重复值并将其删除。

CREATE TRIGGER [dbo].[deleteduplicate] 
ON [dbo].[products]
AFTER INSERT
AS
BEGIN
    declare @productname nvarchar(20),@prodcutid int
    select productname=@productname,productid=@prodcutid from inserted
    if exists (select productname=@productname from products)
    begin
        delete products
        where @productname=productname
    end

END
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 5

您不会在触发器中删除重复的值。您可以使用约束来确保数据库完整性。在这种情况下是一个unique约束。使用唯一约束或索引定义:

alter table t add constraint unq_t_col1_col2_col3 on (col1, col2, col3);
Run Code Online (Sandbox Code Playgroud)

当然,这对于已经有数据并且有重复项的表将不起作用。因此,您将它们删除一次:

with todelete as (
      select t.*, row_number(*) over (partition by col1, col2, col3 order by co1l) as cnt
      from t
     )
delete from todelete
    where seqnum > 1;
Run Code Online (Sandbox Code Playgroud)