SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 sync data from different DB
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

peace
Constraint Violating Yak Guru

410 Posts

Posted - 03/25/2013 :  10:20:54  Show Profile  Reply with Quote
how can i insert new record from DB 1 to DB 2.
if already exist, just need to update to sync it.

i tried this but it doesn't work.

if exists
(select distinct a.* from tableA a
inner join tableB b
on a.col1=b.col1
)

update tableA
set a.col1=b.col1,
a.col2=b.col2

from tableB b

inner join tableA a
on a.col1=b.col1

else

INSERT INTO tableA (col1,col2)
select * from tableB
where not exists (select * from tableA)

TG
Flowing Fount of Yak Knowledge

USA
6062 Posts

Posted - 03/25/2013 :  10:55:29  Show Profile  Reply with Quote
You should let us know why it "doesn't work" - ie: error, incorrect results, etc.

At first glance I'd guess the reason it "doesn't work" your final insert where not exists statement. If there are ANY rows in tableA then the where clause will never be satisfied.

Sql Server 2008 and later offers a MERGE statement. That may be better for you.

Be One with the Optimizer
TG
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52317 Posts

Posted - 03/25/2013 :  11:21:50  Show Profile  Reply with Quote
it should be

if exists 
(select a.* from tableA a 
inner join tableB b 
on a.col1=b.col1 
)
update tableA
set a.col1=b.col1,
a.col2=b.col2
from tableB b
inner join tableA a
on a.col1=b.col1 
else
INSERT INTO tableA (col1,col2)
select * from tableB b
where not exists (select * from tableA where col1 = b.col1)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

peace
Constraint Violating Yak Guru

410 Posts

Posted - 03/25/2013 :  11:26:34  Show Profile  Reply with Quote
Oh thanks. I missed out here:

.....
else
INSERT INTO tableA (col1,col2)
select * from tableB b
where not exists (select * from tableA
where col1 = b.col1)
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000