SQL:如果不存在则先插入然后更新

时间:2018-11-04 10:59:06

标签: sql sql-server tsql

我知道有很多关于此主题的帖子,但这略有不同。我有2个表variant_detail (vad)variant_external_analysis (vaea)vaea主要为空,我需要为vad中的所有行进行更新。如果我在vaea中插入并且该行已经存在,则会复制该行,从而破坏数据库。

在1行测试中,我已经解决了以下问题:

IF NOT EXISTS (SELECT vaea_vad_id FROM variant_external_analysis 
            JOIN variant_detail ON vad_id = vaea_vad_id 
            WHERE vad_variant_code = 16469)
BEGIN
    INSERT variant_external_analysis (vaea_vad_id) 
    SELECT vad_id
    FROM variant_detail
END

UPDATE variant_external_analysis

SET vaea_last_amended_on = GETDATE(), vaea_last_amended_by = 13, vaea_n_1 = 1

FROM variant_external_analysis
JOIN variant_detail ON vad_id = vaea_vad_id

WHERE vad_variant_code = 16469

这很好,直到我删除WHERE语句,这样它才会影响整个表。下面的代码可以正确更新,但现在不再插入

IF NOT EXISTS (SELECT vaea_vad_id FROM variant_external_analysis

JOIN variant_detail ON vad_id = vaea_vad_id 

            WHERE vad_id = vaea_vad_id)
BEGIN
    INSERT variant_external_analysis (vaea_vad_id) 
    SELECT vad_id
    FROM variant_detail
END

UPDATE variant_external_analysis

SET vaea_last_amended_on = GETDATE(), vaea_last_amended_by = 13, vaea_n_1 = 1

FROM variant_external_analysis
JOIN variant_detail ON vad_id = vaea_vad_id

我可能缺少简单的东西。

2 个答案:

答案 0 :(得分:2)

代码看起来与T-SQL非常相似,因此下面是在MS SQL Server中使用MERGE的示例:

merge variant_external_analysis vea
--using here left join (along with where condition) we'll get only rows 
--that are in variand_details but aren't in variant_external_analysis
using(select vd.vad_id 
  from variant_detail vd
  left join variant_external_analysis vaea on vd.vad_id = vaea.vaea_vad_id 
  where vaea.id is null) t --or any another column of vaea
on (vea.vaea_vad_id = t.vad_id)
when not matched then 
    insert (vaea_vad_id, vaea_last_amended_on, vaea_last_amended_by, vaea_n_1)
    values(t.vad_id, getdate(), 13, 1)
;

UPD 要用单行测试子句:

  1. code子句中添加using作为返回列
  2. 使用when条件扩展code子句

merge variant_external_analysis vea
    --using here left join (along with where condition) we'll get only rows 
    --that are in variand_details but aren't in variant_external_analysis
    using(select vd.vad_id, vd.vad_variant_code 
      from variant_detail vd
      left join variant_external_analysis vaea on vd.vad_id = vaea.vaea_vad_id 
      where vaea.id is null) t --or any another column of vaea
    on (vea.vaea_vad_id = t.vad_id)
    when not matched and t.vad_variant_code = 16469 then 
        insert (vaea_vad_id, vaea_last_amended_on, vaea_last_amended_by, vaea_n_1)
        values(t.vad_id, getdate(), 13, 1)
    ;

答案 1 :(得分:0)

where子句中包含“ vad_variant_code = vad_id = vaea_vad_id”。