2

我的任务是同步 2 个表(两者都是相同的)。它们每个有 60 列。表 A 是最初将被填充的主表。我需要创建一个存储过程(完成),它将合并这两个表并在调用时使用相同的确切数据(更新、插入、删除)填充两者。我将如何使用 SQL 中的 MERGE 函数来实现这一点?我查看了 MSDN 文档和 technet 上的类似文档,但我对入门感到很困惑。我是否需要指定需要合并的每个字段?还是我缺少一个简单的调用来执行此操作?

4

2 回答 2

6

这是 MERGE 语句的简单示例的链接:

http://www.simple-talk.com/sql/learn-sql-server/the-merge-statement-in-sql-server-2008/

基本语法如下:

MERGE table1
USING table2
ON table1.id = table2.id
WHEN MATCHED THEN
--Do an update here
WHEN NOT MATCHED BY TARGET THEN
--Do an insert here (or a delete)
;

你也可以使用WHEN NOT MATCHED BY SOURCE

于 2013-02-13T17:57:37.993 回答
6

超过 60 列是一个很大的数字!当我需要同步 2 个相同的表时,我会:

;WITH tbl_to_synch as (
    -- Prepare table to update,
    Select *,chk = CHECKSUM(*) from [dbo].[tableA]
)
MERGE tbl_to_synch as [Target]
USING (Select *,chk = CHECKSUM(*) from [dbo].[tableB]) as [source]
ON [Target].key = [source].key
WHEN MATCHED AND [Target].chk <> [source].chk THEN 
-- UPDATE ONLY row that is changed
UPDATE
    SET 
        column01 = [source].[column01]
        ,column02 = [source].[column01]
        -- .... 
        ,column59 = [source].[column59]
        ,column60 = [source].[column59]

WHEN NOT MATCHED BY TARGET THEN
    insert (column01, column02, ...,column59,column60)
    values (column01, column02, ...,column59,column60)
WHEN NOT MATCHED BY SOURCE THEN DELETE
-- Show what is changed
OUTPUT $action, ISNULL(INSERTED.key,DELETED.key);
于 2017-05-16T10:32:21.423 回答