当前位置: 代码迷 >> Sql Server >> SQL 2014的一个插入/更新 两个链接表的有关问题
  详细解决方案

SQL 2014的一个插入/更新 两个链接表的有关问题

热度:452   发布时间:2016-04-24 08:50:13.0
SQL 2014的一个插入/更新 两个链接表的问题。
table1 和 table2 如下所示:name,pid,tid 是联合主键
table1 和 table2 的pid 和 tid 相反对应,匹配出现,表示同一条记录; 但所在行顺序可能不一至;比如Table1里面zhao, 1, 3 和 Table2里面 zhao, 3, 1 是同一条记录.

Table1
name, pid, tid, result
zhao, 1, 2, a1
zhao, 1, 3, b2
qian, 3, 1, a2
sun, 1, 1, ff
li, 3, 1, a1

Table2
name, pid, tid, result
zhao, 2, 1, a1
li, 1, 3, a1
sun, 1, 1, ff
qian, 1, 3, a2
zhao, 3, 1, b2


现在要一个SQL语句插入一条记录,如果记录已有(根据name, pid, tid)则对两个表进行更新 (result),没有则插入数据到两表。

比如要插入/更新 ('zhao','1','3', 'c2'), 由于记录已经存在,则更新这条记录的result 为 'c2' 
比如要插入/更新 ('zhao','1','4', 'c2'), 由于记录不存在,则插入这条数据到table1和table2.
------解决思路----------------------
LZ 可以研究一下 Merge 。
------解决思路----------------------
大概就是这样:

if exists(select 1 from table1 where name='zhao' and pid='1' and tid='3') and
   exists(select 1 from table2 where name='zhao' and pid='3' and tid='1') and
begin
update table1
set result='c2'
where name ='zhao' and pid='1' and tid='3';

update table3
set result='c2'
where name ='zhao' and pid='3' and tid='1'
end
else
begin
insert into table1 values('zhao','1','3', 'c2');
insert into table2 values('zhao','3','1', 'c2');
end;
------解决思路----------------------
MERGE Table2 AS d  -- 目标表
USING 
Table1 AS s -- 源表
ON s.pid = d.tid and s.tid = d.pid and a.name = d.name
WHEN NOT MATCHED BY SOURCE THEN
DELETE
WHEN NOT MATCHED BY TARGET THEN 
INSERT(name, pid, tid, result) 
VALUES(s.name, s.tid, s.pid, s.result) 
WHEN MATCHED THEN 
UPDATE SET d.result = s.result;
  相关解决方案