我有两个表,我需要比较数据并更新一个表记录。请让我知道如何做到这一点,我试图不使用合并。这是方案
Proj1表 这是第一个需要同步数据的表
ID Text
1 R1
2 R2
3 R3
Proj2表 这是正在进行数据更新的表
ID Text Active
3 R1 1
4 R3 1
5 R4 1
在这两个表之间的文本字段上进行比较后,结果应类似于以下内容。我们正在将Proj2中的数据同步到类似于Proj1。
ID Text Active
3 R1 1 (Ignore as it exists in both tables)
4 R3 1 (Ignore as it exists in both tables)
5 R4 0 (Update to inactive as it does not exist Proj1 table)
6 R2 1 (Insert as it does not exist in Proj2 table)
答案 0 :(得分:2)
merge [Proj2Table] target
using ( select [id], [text] from [Proj1Table] ) source ([id], [text] )
on target.[id] = source.[id]
when not matched by source
then update
set target.[Active] = 0
when not matched by target
then insert
([id], [text] )
values( source.[id], source.[text] )
答案 1 :(得分:2)
-- update records in table 2 that cannot be found in table 1
update P2
set P2.[Active] = 0
from [Proj2Table] as P2
left join [Proj1TAble] as P1 on P1.[text] = P2.[text]
where P1.[id] is null;
-- update records in table 2 that can be found in table 1
update P2
set P2.[Active] = 1
from [Proj2Table] as P2
join [Proj1TAble] as P1 on P1.[text] = P2.[text];
-- insert missing records from table 1 into table 2 with active bit set
insert into [Proj2Table] ([id] , [text] , [active] )
select [id] , [text] , [active] = 1
from [Proj1Table] as P1
where not exists (select 1 from [Proj2Table] as P2 where P2.[text] = P1.[text])
;
不确定[id]列是否匹配或是否为pk / identity / sequence
答案 2 :(得分:1)
如果你真的不能使用MERGE
,你可以简单地将其拆分为更新和插入查询:
INSERT INTO @Proj2(Text, Active)
SELECT Text,1 FROM @Proj1 p1
WHERE NOT EXISTS(
SELECT *
FROM @Proj2 p2
WHERE p2.Text = p1.Text
);
UPDATE
p2
SET
p2.Active = CASE WHEN p1.id is null THEN 0 ELSE 1 END
FROM
@Proj2 p2
LEFT JOIN
@Proj1 p1
ON
p2.Text = p1.Text;
这假设您的ID是自动增量。
Thsi与Zak的新答案非常相似,但合并了2个更新查询。
答案 3 :(得分:0)
另一种方法是使用光标,如果你真的不想使用MERGE
-declare第一个表上的一个光标并滚动该行,然后对于每一行选择第二个表中相应的行和ac,如果找到/未找到...
虽然不是与性能相关的最佳建议......