日期:2014-05-17 浏览次数:20542 次
--Merge表同步功能测试
--2010.10.28
--wgl
-------------------------------------------------------
--建立环境
IF OBJECT_ID('B1') IS NOT NULL DROP TABLE B1
IF OBJECT_ID('B2') IS NOT NULL DROP TABLE B2
GO
CREATE TABLE B1 (ID1 INT,VAL1 VARCHAR(50),l1 int,l2 int,l3 int)
CREATE TABLE B2 (ID2 INT,VAL2 VARCHAR(50),l1 int,l2 int,l3 int)
GO
INSERT INTO B1 VALUES(1,'A',1,1,1),(2,'B',2,2,2),(3,'C',3,3,3),(4,'D',4,4,4)
GO
--SELECT * FROM B1
--SELECT * FROM B2
--同步语句 Merge,T1与T2同步。
MERGE INTO B2 AS tb_target USING B1 AS tb_source ON tb_target.id2=tb_source.id1
WHEN NOT MATCHED BY TARGET THEN INSERT(id2,val2,l1,l2,l3) VALUES(id1,val1,l1,l2,l3)
WHEN NOT MATCHED BY SOURCE THEN DELETE
WHEN MATCHED THEN UPDATE SET tb_target.val2=tb_source.val1 --AND tb_target.val2<>tb_source.val1
OUTPUT $ACTION,ISNULL(DELETED.ID2,INSERTED.ID2) AS ID,DELETED.VAL2,DELETED.l1,DELETED.l2,DELETED.l3,INSERTED.VAL2,INSERTED.l1,INSERTED.l2,INSERTED.l3;
--输出结果:
/*
%ACTION ID VAL2 VAL2
----------------------
INSERT 1 NULL A
INSERT 2 NULL B
INSERT 3 NULL C
*/
--T2 内容:
/*
ID2 VAL2
--------
1 A
2 B
3 C
*/
--这说明T1的数据已经同步到T2了。现在做一些其他操作,修改,更新,插入,删了。
UPDATE B1 SET VAL1='E' WHERE ID1=2
GO
DELETE FROM B1 WHERE ID1 =3
GO
INSERT B1 VALUES (5,'F',5,5,5)
GO
UPDATE B1 SET l3=99999 WHERE ID1=4
GO
SELECT * FROM B1
SELECT * FROM B2
--结果:
/*
ID1 VAL1
--------
1 A
2 E
5 F
*/
--修改之后,再运行MERGE语句。
MERGE INTO B2 AS tb_target USING B1 AS tb_source ON tb_target.id2=tb_source.id1
WHEN NOT MATCHED BY TARGET THEN INSERT(id2,val2,l1,l2,l3) VALUES(id1,val1,l1,l2,l3) --如果与源表不匹配,则插入
WHEN NOT MATCHED BY SOURCE THEN DELETE --如果源表没有,则删除
WHEN MATCHED THEN UPDATE SET tb_target.val2=tb_source.val1,tb_target.l1=tb_source.l1,tb_target.l2=tb_source.l2,tb_target.l3=tb_source.l3 --AND tb_target.val2<>tb_source.val1 全部更新
OUTPUT $ACTION,ISNULL(DELETED.ID2,INSERTED.ID2) AS ID,DELETED.VAL2,DELETED.l1,DELETED.l2,DELETED.l3,INSERTED.VAL2,INSERTED.l1,INSERTED.l2,INSERTED.l3;
--执行结果:
/*
$ACTION ID VAL2 VAL2
------------------------
INSERT 5 NULL F
UPDATE 2 B E
DELETE 3 C NULL
*/
--查询T2的内容:
/*
ID2 VAL2
--------
1 A
2 E
5 F
*/
--T2 的内容已经正明同步了。