如何防止重复插入SQL Server

时间:2015-04-14 07:14:46

标签: sql sql-server vb.net

我有一张包含数百万条记录的表格。

我有这个问题:

INSERT INTO t1 (recordA, recordB, inserttime) 
   SELECT recordA, recordB, GETDATE() 
   FROM t1 as l1 
   WHERE 
      l1.id_comp = @id_comp 
      AND l1.id_sq NOT IN (SELECT l2.id_sqa 
                           FROM leghe_formazioni as l2 
                           WHERE l2.id_comp = @id_comp)

有时重复记录,有时不重复。

重复记录具有相同的插入时间。

3 个答案:

答案 0 :(得分:2)

在执行INSERT之前检查记录是否已存在:

IF NOT EXISTS (SELECT recordA, recordB, GETDATE() 
FROM t1 as l1 
WHERE 
    l1.id_comp = @id_comp 
    AND l1.id_sq NOT IN (
        SELECT l2.id_sqa 
        FROM leghe_formazioni as l2 
        WHERE l2.id_comp=@id_comp
    ))
INSERT INTO t1 (recordA, recordB, inserttime) 
SELECT recordA, recordB, GETDATE() 
FROM t1 as l1 
WHERE 
    l1.id_comp = @id_comp 
    AND l1.id_sq NOT IN (
        SELECT l2.id_sqa 
        FROM leghe_formazioni as l2 
        WHERE l2.id_comp=@id_comp
    )

答案 1 :(得分:0)

检查这些主题:

MySQL/PHP Inserting the same row twice

MYSQL avoid inserting same row twice

MySQL Rows Inserted Twice

由于您没有真正发布有关您的问题的详细信息,我担心没有多少人可以提供帮助。

您可以随时更改查询,以便在插入之前检查行是否存在。或者尝试选择某些数据,如果结果为空则表示数据库中没有此类数据。

答案 2 :(得分:0)

你可以在sql中这样做:

INSERT INTO t1 (recordA, recordB, inserttime) 
SELECT recordA, recordB, GETDATE() 
FROM t1 as l1 
WHERE 
    l1.id_comp = @id_comp 
    AND l1.id_sq NOT IN (
        SELECT l2.id_sqa 
        FROM leghe_formazioni as l2 
        WHERE l2.id_comp=@id_comp
    )
    and not exists (
      select 1 from t1 
      where t1.recordA = li.recordA and t1.recordB = li.recordB)