如果记录存在,则更新其他插入

时间:2009-10-27 11:58:39

标签: sql sql-server sql-server-2008 merge upsert

我正在尝试在两个SQL Server 2008表之间移动一些数据。如果Table2中的记录与Table1中的电子邮件一起存在,则使用Table1中的数据更新该记录,否则插入新记录。

在表1中,我有许多列;名字,姓氏,电子邮件等。

如果表1中的电子邮件存在,我不太确定如何构建查询以更新Table2,如果表2中不存在Table1的电子邮件,则不能插入新行。

我尝试在Google上进行一些搜索,但大多数解决方案似乎都是通过创建一些存储过程来实现的。所以我想知道是否有人可能知道如何构建一个可能起作用的合适查询?

3 个答案:

答案 0 :(得分:21)

我认为MERGE就是你想要的。

答案 1 :(得分:11)

MERGE
INTO    table2 t2
USING   table1 t1
ON      t2.email = t1.email
WHEN MATCHED THEN
UPDATE
SET     t2.col1 = t1.col1,
        t2.col2 = t1.col2
WHEN NOT MATCHED THEN
INSERT  (col1, col2)
VALUES  (t1.col1, t1.col2)

答案 2 :(得分:1)

Microsoft在SQL表之间发布了a tool to compare data,在某些情况下这可能是个不错的选择。

编辑:忘记提及,它还会生成一个脚本来插入/更新丢失或不同的行。

为了完整起见,我破解了这个查询,它可以执行您想要的操作,它会更新现有的table2记录,并根据电子邮件地址添加缺少的记录。

下面的“更新”和“插入缺失”查询是您想要的。

BEGIN TRAN

create table #table1 (id int, fname varchar(20), email varchar(20))
insert into #table1 values (1, 'name_1_updated', 'email_1')
insert into #table1 values (3, 'name_3_updated', 'email_3')
insert into #table1 values (100, 'name_100', 'email_100')


create table #table2 (id int, fname varchar(20), email varchar(20))
insert into #table2 values (1, 'name_1', 'email_1')
insert into #table2 values (2, 'name_2', 'email_2')
insert into #table2 values (3, 'name_3', 'email_3')
insert into #table2 values (4, 'name_4', 'email_4')

print 'before update'
select * from #table2

print 'updating'
update #table2
set #table2.fname = t1.fname
from #table1 t1
where t1.email = #table2.email

print 'insert missing'
insert into #table2
select * from #table1
where #table1.email not in (select email from #table2 where email = #table1.email)

print 'after update'
select * from #table2

drop table #table1
drop table #table2

ROLLBACK