如何使用merge语句将一个临时表拆分为两个,以便从Staging加载到RealtionalDB?

时间:2016-03-03 16:18:59

标签: sql tsql merge common-table-expression

我有以下表格。我想从test1表中将值插入companyGroup和Comapany。什么是更好的方式CTE或直接使用合并,我怎么能用tsql做到这一点。 Test1在数据库A上,公司和公司组在数据库B上。

    create table test1
  (
  companyID int identity
  ,CompanyName Varchar(50)
  ,[Group] Varchar(5)
  )

  INSERT INTO (CompanyName, [Group]) values ('Unknown', '0')
  INSERT INTO (CompanyName, [Group]) values ('APPLE', 'IOS')
  INSERT INTO (CompanyName, [Group]) values ('Google', 'Android')
  INSERT INTO (CompanyName, [Group]) values ('Samsung', 'Android')
  INSERT INTO (CompanyName, [Group]) values ('Lg', 'IOS')

  create table CompanyGroup
  (
     Groupkey int identity (0,1) primary key
    ,GroupName varchar(5)  
  ) ;

  INSERT INTO (GroupName) VALUES ('Unknown')

  create table Company
  (
    compnayKey int identity (0,1) primary key
    ,CompanyName Varchar(50)
    ,companyGroupKey int References CompanyGroup(GroupKey)
  )

  INSERT INTO (CompanyName,companyGroupKey) VALUES ('Unknown',0)

当我将值插入公司时如何将组转换为int?有任何想法吗?什么是这个负载的最佳TSQL。

1 个答案:

答案 0 :(得分:1)

尝试使用:

  INSERT INTO CompanyGroup(GroupName)
  SELECT [Group]
  FROM test1
  WHERE NOT EXISTS(SELECT 1 
                   FROM CompanyGroup 
                   WHERE GroupName = [Group]);

  MERGE Company AS target
    USING (SELECT t.CompanyName, g.Groupkey
            FROM test1 AS t
            LEFT JOIN CompanyGroup AS g ON t.[Group] = g.GroupName
        ) AS source
    ON (target.CompanyName = source.CompanyName 
        AND target.companyGroupKey = source.Groupkey)
  WHEN NOT MATCHED THEN
    INSERT (CompanyName, companyGroupKey)
    VALUES (source.CompanyName, source.Groupkey);