0

我有一个包含数百万条记录的 SQL DB 表。如果新记录不是重复记录,我想插入一条记录。但我不想检查是否存在重复记录。有没有办法直接插入,如果存在重复记录就忽略新插入?

4

2 回答 2

1

如果您要从Table

INSERT INTO INSERT_TABLE_NAME
(.....)
SELECT
(.....)
FROM TABLE_NAME T1
INNER JOIN INSERT_TABLE_NAME T2
ON T1.COLUMN_NAME1<>T2.COLUMN_NAME1
OR T1.COLUMN_NAME2<>T2.COLUMN_NAME2
OR ...

如果您要插入记录values

INSERT INTO INSERT_TABLE_NAME
(.....)
VALUES
(.....)
WHERE 
ON VALUE1<>T2.COLUMN_NAME1
OR VALUE2<>T2.COLUMN_NAME2

我的解决方案仅适用于您表中的列数量合理的情况。

Ofcouse @Damien_The_Unbeliever 提供了更好的解决方案。但是你不能在某个点之后实现它。

于 2013-06-07T12:36:37.160 回答
1

You might be able to achieve what you want by applying a UNIQUE INDEX on the table and specifying IGNORE_DUP_KEY ON:

Specifies the error response when an insert operation attempts to insert duplicate key values into a unique index. The IGNORE_DUP_KEY option applies only to insert operations after the index is created or rebuilt. The option has no effect when executing CREATE INDEX, ALTER INDEX, or UPDATE. The default is OFF.

ON

A warning message will occur when duplicate key values are inserted into a unique index. Only the rows violating the uniqueness constraint will fail.

So the insert will succeed for new unique rows, but you can't avoid the warning message.


You would create this index across all columns by which you're defining uniqueness/duplicates - which may or may not be all columns in the table - you haven't given us a definition to work from.

于 2013-06-07T12:25:29.600 回答