SQL Server 将现有表复制到新表中但跳过重复记录

Posted

技术标签:

【中文标题】SQL Server 将现有表复制到新表中但跳过重复记录【英文标题】:SQL Server copy existing table into new one but skip duplicate records 【发布时间】:2018-10-12 16:59:09 【问题描述】:

所以我有一个空的目标表,我想从现有的报告表中复制所有记录。但是,现有的 Report 表没有任何主键,而我的新目标表有。我想复制现有报告表中的所有记录,这些记录在“Report.field1”和“Report.field2”上不重复,并且它们在任何一个中都不为 NULL。

有没有一种快速而肮脏的方法来做到这一点?喜欢:

INSERT INTO target REPORT
ON CONFLICT SKIP

【问题讨论】:

【参考方案1】:

请看: How to avoid duplicate SQL data while executing the INSERT queries without source database

IF not exists(select * from Report where field1 = @field1 and field2 = @field2) and @field1 is not null and @field2 is not null
    INSERT INTO Report (..., ..., ...) 
        VALUES (..., ..., ...)

【讨论】:

原始表中有很多字段,我宁愿不必手动写出。有没有办法更简洁地构造这个语句并达到相同的结果? ***.com/questions/4526461/…

以上是关于SQL Server 将现有表复制到新表中但跳过重复记录的主要内容,如果未能解决你的问题,请参考以下文章