Thursday 4 July 2013

Insert/update using more than one database placed on different servers


Introduction:


Most of the time it needs to connect more than one database to perform DML queries. We can insert or update records from our database to another database. But sometime these database can be on different servers too. In that case we need to first establish communication between these servers. Please follow the below steps:

Code:


sp_configure 'show advanced options', 1;
RECONFIGURE;
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
set IDENTITY_INSERT [table name] off
insert into [table name](col1,col2,col3)
SELECT mycol1,mycol2,ycol3 from OpenDataSource('SQLNCLI', 'Data Source=192.168.0.0;User ID=username;Password=pass').[database].[tablename] v
 WHERE v.id>12


update v
set col1=v1.mycol
from [table1] v
inner join OpenDataSource('SQLNCLI', 'Data Source=192.168.0.0;User ID=username;Password=pass').[database].[tablename] v1
on v.id=v1.id

No comments:

Post a Comment