如何向表中添加一个触发器以删除重复项

huangapple go评论58阅读模式
英文:

How to add a trigger to delete duplicates in table

问题

以下是翻译好的内容:

"Hi,我有一个如下所示的表格:

[dbo].[table1](
[predictions] [int] NULL,
[timestamp] [datetime] NULL,
[train1] [int] NULL,
[train2] [int] NULL)

我正在使用 dbx job 向这个表格插入数据,有时候在表格中会出现时间戳列的重复项。

当发生重复项时,我想在数据库中添加一个触发器来删除它们。

现在,我正在手动运行以下查询来删除重复值:

With duplicates As (Select *, ROW_NUMBER() Over (PARTITION by timestamp Order by timestamp) as Duplicate From table1) select From duplicates Where Duplicate > 1 ;

非常感谢任何帮助!"

英文:

Hi I have a table like this below:

[dbo].[table1](
	[predictions] [int] NULL,
	[timestamp] [datetime] NULL,
	[train1] [int] NULL,
	[train2] [int] NULL)

I'm inserting data into this table with dbx job..and sometimes we get duplicates for timestamp column in the table.

I want to add a trigger to the db to delete duplicates when it happens.

I'm manually deleting duplicate values running this query below now.

With duplicates As (Select *, ROW_NUMBER() Over (PARTITION by timestamp Order by timestamp) as Duplicate From table1) select From duplicates Where Duplicate > 1 ;

Any help is greatly appreciated!

答案1

得分: 4

你可以使用不太为人知的 IGNORE_DUP_KEY 选项

ALTER TABLE dbo.table1
ADD CONSTRAINT uq_table1_timestamp
  UNIQUE (timestamp)
  WITH (IGNORE_DUP_KEY = ON);

这将自动(并静默地)忽略重复的行插入。

请注意,这不会删除现有的重复项,您首先需要运行:

WITH cte AS (
    SELECT *,
      rn = ROW_NUMBER() OVER (PARTITION BY timestamp ORDER BY timestamp)
    FROM yourTable
)
DELETE cte
WHERE rn > 1;
英文:

You can use the little known IGNORE_DUP_KEY option.

ALTER TABLE dbo.table1
ADD CONSTRAINT uq_table1_timestamp
  UNIQUE (timestamp)
  WITH (IGNORE_DUP_KEY = ON);

This will automatically (and silently) ignore inserts of rows which are duplicates.

Note that this does not remove existing duplicates, you first need to run:

WITH cte AS (
    SELECT *,
      rn = ROW_NUMBER() OVER (PARTITION BY timestamp ORDER BY timestamp)
    FROM yourTable
)
DELETE cte
WHERE rn > 1;

huangapple
  • 本文由 发表于 2023年5月22日 21:21:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定