我在表 1 上有这样的数据:在此处输入图像描述
IdT1 , IdT1组
11 , 30
12 , 30
13 , 30
并且在表 2 上喜欢:在此处输入图像描述
IdT2、IdT1、详细信息、同步
1 , 11 , A , 插入
2 , 11 , B , 插入
3、12、A、插
4、12、C、插
我有这样的 tblSource:在此处输入图像描述
IdT2,IdT1,详细信息
1、11、A
2、11、B
5、11、C
我从以下位置获得了 tblSource:
Select Top 1 From Tbl2 where IdT1Group = 30
我希望我可以更新 Tbl2 成为:在此处输入图像描述
IdT2, IdT1, Detail, Synchronise
1 11 A updated
2 11 B updated
5 11 C inserted
3 12 A updated
4 12 B updated
6 12 C inserted
7 13 A inserted
8 13 B inserted
9 13 C inserted
这是我用来得到我期望的代码:
Declare @IdT1Group integer = 30
;WITH tblTbl2
AS (SELECT table2.* FROM table2 INNER JOIN table1 ON table2.IdT1 = table1.IdT1 AND IdT1Group = @IdT1Group)
MERGE INTO tblTbl2 AS tblTarget
USING (SELECT tblT2.*, table1.IdT1 AS T1Id FROM tbl2 AS tblT2 CROSS JOIN table1 where IdT1Group = @IdT1Group)
AS tblSource ON tblTarget.IdT1 = tblSource.T1Id And tblTarget.IdT2 = tblSource.IdT2
WHEN MATCHED THEN
UPDATE
SET Detail = tblSource.Detail, Synchronise = 'updated'
WHEN NOT MATCHED BY SOURCE THEN
DELETE
WHEN NOT MATCHED BY TARGET THEN
INSERT (IdT1, Detail, Synchronise)
VALUES (tblSource.T1Id, tblSource.Detail, 'inserted');
但这就是我得到的:在此处输入图像描述
IdT2 IdT1 Detail Synchronise
1 11 A updated
2 11 B updated
5 11 C inserted
6 12 A inserted
7 12 B inserted
8 12 C inserted
9 13 A inserted
10 13 B inserted
11 13 C inserted
这段代码让我做一些试验:
drop table if exists table1
create table table1(idt1 int, idt1group int)
insert into table1 values (11,30),(12,30),(13,30)
drop table if exists table2
create table table2 (idt2 int, idt1 int, detail varchar(2), Synchronise varchar(15))
insert into table2 values (1,11,'A', 'Inserted'),(2,11,'B', 'Inserted'),
(3,12,'A', 'Inserted'),
(4,12,'B', 'Inserted')
drop table if exists tbl2
create table tbl2 (idt2 int, idt1 int, detail varchar(2), Synchronise varchar(15))
insert into tbl2 values (1, 11,'A', 'Inserted'),
(2,11,'B', 'Inserted'), (5,11,'C', 'Inserted')
Declare @IdT1Group integer = 30
SELECT table1.IdT1 AS T1Id, tblT2.* FROM tbl2 AS tblT2 CROSS JOIN table1 where IdT1Group = @IdT1Group
;WITH tblTbl2
AS (SELECT table2.* FROM table2 INNER JOIN table1 ON table2.IdT1 = table1.IdT1 AND IdT1Group = @IdT1Group)
MERGE INTO tblTbl2 AS tblTarget
USING (SELECT tblT2.*, table1.IdT1 AS T1Id FROM tbl2 AS tblT2 CROSS JOIN table1 where IdT1Group = @IdT1Group)
AS tblSource ON tblTarget.IdT1 = tblSource.T1Id And tblTarget.IdT2 = tblSource.IdT2
WHEN MATCHED THEN
UPDATE
SET Detail = tblSource.Detail, Synchronise = 'updated'
WHEN NOT MATCHED BY SOURCE THEN
DELETE
WHEN NOT MATCHED BY TARGET THEN
INSERT (IdT1, Detail, Synchronise)
VALUES (tblSource.T1Id, tblSource.Detail, 'inserted');
select * From Table2