我应该如何将这些数据迁移到这些Sql Server表中?

时间:2010-10-18 00:59:36

标签: sql sql-server tsql sql-server-2008 data-migration

我希望将单个表中的一些数据迁移到这些新的THREE表中。

这是我的目标架构:

alt text

请注意,我需要插入第一个Location表..抓取SCOPE_IDENTITY() ..然后将行插入BoundaryCountry表。

SCOPE_IDENTITY()杀了我:(意思是,我只能通过CURSORS看到这样做的方法。有没有更好的选择呢?

更新

这是DB Schema的脚本....

位置

CREATE TABLE [dbo].[Locations](
    [LocationId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    [OriginalLocationId] [int] NOT NULL,
 CONSTRAINT [PK_Locations] PRIMARY KEY CLUSTERED 
(
    [LocationId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) 

国家

CREATE TABLE [dbo].[Locations_Country](
    [IsoCode] [nchar](2) NOT NULL,
    [LocationId] [int] NOT NULL,
 CONSTRAINT [PK_Locations_Country] PRIMARY KEY CLUSTERED 
(
    [LocationId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Locations_Country]  WITH CHECK ADD  CONSTRAINT [FK_Country_inherits_Location] FOREIGN KEY([LocationId])
REFERENCES [dbo].[Locations] ([LocationId])
GO

ALTER TABLE [dbo].[Locations_Country] CHECK CONSTRAINT [FK_Country_inherits_Location]
GO

边界

CREATE TABLE [dbo].[Boundaries](
    [LocationId] [int] NOT NULL,
    [CentrePoint] [varbinary](max) NOT NULL,
    [OriginalBoundary] [varbinary](max) NULL,
    [LargeReducedBoundary] [varbinary](max) NULL,
    [MediumReducedBoundary] [varbinary](max) NULL,
    [SmallReducedBoundary] [varbinary](max) NULL,
 CONSTRAINT [PK_Boundaries] PRIMARY KEY CLUSTERED 
(
    [LocationId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Boundaries]  WITH CHECK ADD  CONSTRAINT [FK_LocationBoundary] FOREIGN KEY([LocationId])
REFERENCES [dbo].[Locations] ([LocationId])
GO

ALTER TABLE [dbo].[Boundaries] CHECK CONSTRAINT [FK_LocationBoundary]
GO

2 个答案:

答案 0 :(得分:5)

如果您按照父/子关系的顺序处理数据,我认为不需要SCOPE_IDENTITY或游标:

INSERT INTO LOCATION
  SELECT t.name,
         t.originallocationid
    FROM ORIGINAL_TABLE t
GROUP BY t.name, t.originallocationid

INSERT INTO COUNTRY 
SELECT DISTINCT
       t.isocode,
       l.locationid
  FROM ORIGINAL_TABLE t
  JOIN LOCATION l ON l.name = t.name
                 AND l.originallocationid = t.originalocationid

INSERT INTO BOUNDARY
SELECT DISTINCT
       l.locationid,
       t.centrepoint,
       t.originalboundary,
       t.largereducedboundary,
       t.mediumreducedboundary,
       t.smallreducedboundary
  FROM ORIGINAL_TABLE t
  JOIN LOCATION l ON l.name = t.name
                 AND l.originallocationid = t.originalocationid

答案 1 :(得分:1)

加载您的位置表后,您可以创建一个将位置与源单表连接的查询。连接标准是自然键(是Name列?),它将返回新的LocationId和Boundary数据。结果将插入到新的边界表中。