如何在不重复我创建的表内的记录的情况下一次又一次地插入?

时间:2013-10-29 08:36:51

标签: sql sql-server

这是我创建的表格:

use DWResourceTask
go
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TESTDimEntity]') AND type in (N'U'))
DROP TABLE [TESTDimEntity]
Go
Create Table TESTDimEntity

(EntityKey int NOT NULL identity PRIMARY KEY,
[EntCode] [nvarchar](8) NOT NULL,
    [Name] [nvarchar](80) NOT NULL,
    [CompanyRegistration] [nvarchar](80) NULL,
    [Active] [int] NOT NULL,
    [AccessLevel] [int] NOT NULL ,
    [SiteURN] [nvarchar](128) NOT NULL,
    [CompanyURN] [nvarchar](128) NOT NULL,
    [SiteName] [nvarchar](30) NOT NULL,
    [SiteDesc] [nvarchar](60) NULL,
    [SiteURL] [nvarchar](512) NOT NULL)

我使用以下脚本插入数据:

Insert into DWResourceTask.dbo.TESTDimEntity
Select e.EntCode, e.Name, CompanyRegistration, e.Active, e.AccessLevel, ss.SiteURN, ss.CompanyURN,
ss.SiteName, ss.SiteDesc, ss.SiteURL
from USA.dbo.Site ss, USA.dbo.LegalEnt e
where ss.localsiteflag = 1
and e.active = 1
UNION ALL
Select e.EntCode, e.Name, CompanyRegistration, e.Active, e.AccessLevel, ss.SiteURN, ss.CompanyURN,
ss.SiteName, ss.SiteDesc, ss.SiteURL
from UK.dbo.Site ss, UK.dbo.LegalEnt e
where ss.localsiteflag = 1
and e.active = 1

并且这个脚本生成了这3行,每列都有自己的数据。


我的问题是......

如果我想反复运行“插入脚本”,它不会附加或复制数据,但它只会更新,只会插入新记录或/和更新现有记录。

是否有任何脚本无法插入当前DimEntity表中已存在的数据?

非常感谢!

1 个答案:

答案 0 :(得分:2)

使用MERGE

WITH c as (
 SELECT ...
   FROM USA.dbo.Site ss 
   JOIN USA.dbo.LegalEnt e
     ON <somejoincondition here!>
   WHERE ss.localsiteflag = 1
      and e.active = 1
 UNION ALL ...)
MERGE INTO TESTDimEntity as t
 USING c
 ON (t.EntCode = c.EntCode)
WHEN MATCHED THEN UPDATE 
 SET t.<field> = c.<field>
WHEN NOT MATCHED THEN INSERT (t.<fields>)
  VALUES (c.<fields>);

您的语句存在一些问题,缺少的JOIN子句最为明显。您应该有一个索引来强制执行任何预期的UNIQUEness。