SQL查询以插入和更新

时间:2019-01-06 09:22:54

标签: sql

我可以在单个SQL查询中一起使用插入查询和更新查询吗?如果有可能,我该如何编写此查询?必须以哪种格式书写。

2 个答案:

答案 0 :(得分:0)

我将发布从源表到目标表的查询复制的片段,以向您提供上下文和有关其工作方式的提示,您可以从那里获取它:

update  dst
set     col1 = src.col1
from    DestinationTable dst
join    SourceTable src
on      src.Key = dst.Key

insert  DestinationTable 
        (Key, col1)
select  Key
,       col1
from    SourceTable src
where   not exists
        (
        select  *
        from    DestinationTable dst
        where   src.Key = dst.Key
        )

答案 1 :(得分:-1)

如果是MySQL,则可以使用REPLACE插入新行或覆盖现有行:

REPLACE INTO test VALUES (1, 'Old', '2014-08-20 18:47:00');