INSERT ... ON DUPLICATE KEY UPDATE比DELETE / INSERT所有记录更快

时间:2013-08-15 06:28:21

标签: mysql tsql linked-server

我正在尝试同步2组表,每组在结构上大致相同,一组在Microsoft SQL Server数据库上,另一组在MySQL数据库上,MSSQL有一个链接服务器到MySQL数据库名为LNK-SVR

我想知道哪个更快,删除一个表中的每个记录并使用INSERT INTO ... SELECT FROM查询再次插入它或使用INSERT...ON DUPLICATE KEY UPDATE以便创建任何新记录并且任何主键违规已更新

1 个答案:

答案 0 :(得分:0)

在Sql Server 2008或更早版本中,您应该使用Merge语句来同步两个表:

请看以下示例: 运行后,两个表(@sourceTable和@targetTable)都有相同的行。

DECLARE @sourceTable TABLE(id INT PRIMARY KEY, somefield VARCHAR(255))

DECLARE @targetTable TABLE(id INT PRIMARY KEY, somefield VARCHAR(255))

INSERT INTO @sourceTable (id, somefield) VALUES(1, 'SourceValue1'),
 (3, 'SourceValue3')

INSERT INTO @targetTable (id, somefield) VALUES(1,
 'TargetValue1'), (2, 'TargetValue2')

SELECT * FROM @sourceTable SELECT * FROM @targetTable

MERGE @targetTable AS target USING @sourceTable AS source
ON target.id = source.id
WHEN MATCHED THEN UPDATE SET somefield = source.somefield
WHEN NOT MATCHED THEN   INSERT (id, somefield) VALUES(id, source.somefield)
WHEN NOT MATCHED BY source THEN DELETE;

SELECT * FROM @sourceTable
SELECT * FROM @targetTable