10

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

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

如果来自 Table1 的电子邮件存在,或者如果来自 Table1 的电子邮件在 Table2 中不存在,我不太确定如何构建查询以更新 Table2。

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

4

3 回答 3

21

我认为MERGE是你想要的。

于 2009-10-27T12:04:00.963 回答
12
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)
于 2009-10-27T23:02:16.450 回答
1

Microsoft 发布了一个工具来比较SQL 表之间的数据,这在某些情况下可能是一个不错的选择。

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

为了完整起见,我破解了这个查询,它可以满足您的需求,它会更新现有的 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
于 2009-10-27T12:08:27.047 回答