If Record Exists, Update Else Insert

后端 未结 3 1838
误落风尘
误落风尘 2021-01-11 17:53

I\'m trying to move some data between two SQL Server 2008 tables. If the record exists in Table2 with the email from Table1 then update that record with the data from Table1

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-11 18:08

    Microsoft released a tool to compare data between SQL tables, this might a good option in certain situations.

    Edit: Forgot to mention, it also generates a script to insert/update missing or different rows.

    For completeness, I hacked up this query which does what you want, it updates existing table2 records, and adds those that are missing, based off the email address.

    The 'updating' and 'insert missing' queries below are the ones you want.

    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
    

提交回复
热议问题