简体   繁体   English

合并SQL Server数据库

[英]Merge SQL Server databases

I'm attempting to merge multiple SQL Server databases into one. 我正在尝试将多个SQL Server数据库合并为一个。 The problem is that one of the tables has an identity field as the primary key. 问题在于,其中一个表具有一个标识字段作为主键。 The table also has two uniqueid fields. 该表还具有两个uniqueid字段。 Something like: 就像是:

datatable:
id pk identity
link1 uniqueid
link2 uniqueid

My initial thought was to run the following script: 我最初的想法是运行以下脚本:

declare @maxId as int
set @maxId = ( SELECT IsNull(MAX(id),0) FROM datatable)
SET IDENTITY_INSERT datatable ON
INSERT INTO database1.datatable id, link1, link2 SELECT id + @maxId, link1, link2 FROM database2.datatable
SET IDENTITY_INSERT datatable OFF

Which works, except that is the query is run multiple times the data gets duplicated. 这是可行的,只是查询会多次重复执行查询。 What would be the best way to make sure a combination of link1 and link2 do not already exist in my table? 确保表中不存在link1和link2组合的最佳方法是什么?

If it was only one column I could use the IN statement, but unfortunately I need both colums to match. 如果只有一列,我可以使用IN语句,但是不幸的是,我需要两个列都匹配。

You mentioned IN so I assume that you want to merge the link columns. 您提到IN,所以我假设您要合并链接列。 This way is safe to run multiple times and avoids the IDENTITY column issue. 这种方法可以安全运行多次,并避免了IDENTITY列问题。

INSERT INTO database1.datatable (link1, link2)
SELECT link1, link2
FROM database2.datatable d2
WHERE NOT EXISTS (SELECT *
    FROM
        database1.datatable d1
    WHERE
        d1.link1 = d2.link1 and d1.link2 and d2.link2)

If it's wrong, you can still use EXISTS/NOT EXISTS to deal with multiple column that an IN clause can not... 如果错了,您仍然可以使用EXISTS / NOT EXISTS来处理IN子句无法处理的多列...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM