我有一个包含这两个表的数据库:
[OLDDB]。[每] [人]
PersonId | FirstName | LastName | Code
2003 | 'Mike' | 'Jordan' | 2
2357 | 'Sara' | 'Jacobs' | 1
3481 | 'John' | 'Gates' | 5
[OLDDB] [萨尔] [客户]
CustomerId | PersonId | CustomerType
830 | 2003 | 3
945 | 2357 | 2
1333 | 3481 | 2
我的新数据库具有相同的表和架构:
[NEWDB]。[每] [人]
PersonId | FirstName | LastName | Code
[NEWDB] [萨尔] [客户]
CustomerId | PersonId | CustomerType
表中的PersonId Person是身份,我可以使用此代码复制人员,但PersonId将与旧数据库不同,因此我不能使用我在下面说的第二个查询来复制客户表中的数据。
INSERT INTO NewDb.per.Person
(FirstName,LastName,Code)
SELECT FirstName,LastName,Code
FROM OldDb.per.Person
INSERT INTO NewDb.Sal.Customer
(PersonId,CustomerType)
SELECT PersonId,CustomerType
FROM OldDb.Sal.Customer
现在我想要一个查询,这样我就可以将数据复制到两个表的新数据库中。
任何帮助都会有很大的帮助。
谢谢。
答案 0 :(得分:2)
您的新数据库为空,如果您想保留旧的PersonId
,可以使用SET IDENTITY_INSERT NewDb.per.Person ON
SET IDENTITY_INSERT NewDb.per.Person ON -- then you could use personId in Insert
INSERT INTO NewDb.per.Person
(PersonId, FirstName,LastName,Code)
SELECT PersonId, FirstName,LastName,Code
FROM OldDb.per.Person
SET IDENTITY_INSERT NewDb.per.Person OFF -- remember set it off after insert
-- then insert new Customer without conflict
INSERT INTO NewDb.Sal.Customer
(PersonId,CustomerType)
SELECT PersonId,CustomerType
FROM OldDb.Sal.Custome
参考链接:SET IDENTITY_INSERT
如果你想要新的PersonId
自动增量,你可以这样做:
----CREATE `OldPersonId` column in your NewDb.per.Person
INSERT INTO NewDb.per.Person
(OldPersonId, FirstName,LastName,Code)
SELECT PersonId, FirstName,LastName,Code
FROM OldDb.per.Person
-- You could insert you new customer Inner join by `OldPersonId` Column
INSERT INTO NewDb.Sal.Customer
(PersonId,CustomerType)
SELECT np.PersonId,CustomerType
FROM OldDb.Sal.Customer oc
INNER JOIN NewDb.per.Person np ON oc.PersonId = np.OldPersonId
-----DELETE `OldPersonId` column in NewDb.per.Person