Different servers SQLSEVER two tables similar structure to achieve data synchronization (trigger)

1, establish a link server

  Create a linked server in pointing to ServerB ServerA in, and make account mapping. addlinkedserver stored procedure to create a linked server parameters details, see the official documentation .

  The first parameter is the custom LNK_ServerA name; second parameter product name, if SQL Server is not provided; the third parameter is the type of drive; fourth parameter is the data source, write SQL Server server address here

exec sp_addlinkedserver 'LNK_ServerB_DatabaseB','','SQLNCLI','192.168.1.101'

  After you configure the linked server using the same local account login remote database default, if there is a different account, the account also needs to be mapped. sp_addlinkedsrvlogin parameters details, see the official documentation .

  The first argument as above; second parameter false that the use of user passwords behind supplied argument landing; third parameter, null so that all local accounts can use the user's password back to the landing linked server, if the third parameter is set to a local SQL server login name, only this user can use the remote account login linked server; the last two are logged into the remote server's user and password.

exec sp_addlinkedsrvlogin 'LNK_ServerB_DatabaseB', 'false ', null, 'user', 'password' 

if you want to remove the above configuration may be as follows
sp_droplinkedsrvlogin Exec 'LNK_ServerB_DatabaseB', null 
Exec sp_dropserver 'LNK_ServerB_DatabaseB', 'droplogins' 
can be taken inside SQLSEVER Stduio manually deleted in the server object \ link configured server can be found in the link server

2, and then triggers the establishment of good to achieve even a different table structure of data sync.
Example: A server establish a student_01 table with name, age, class column, to establish a student same table as the table structure on the server B.
Add or modify data through the server A, while the server B to add or edit data
defined linked server named [LINK_DB]


CREATE trigger [dbo].[trig_to_DB]
on [dbo].[student_01]
after insert ,update
as
begin

declare @name varchar(50);
declare @age int;
declare @class varchar(50);
declare @tname varchar(50);

select @name = name , @age =age , @class = class
from inserted

if(len(@name)!= 0)
select @tname =name from [LINK_DB].[数据库名].[dbo].[student] where name = @name
if(LEN(@tname)!= 0)
begin
update [LINK_DB].[数据库名].[dbo].[student] set age = @age,class = @class where name = @tname
end
else
begin
insert into [LINK_DB].[数据库名].[dbo].[student](name,age,class) values(@name,@age,@class)
end
end

 

After successfully saved, add or modify server A data student_01 table, the server B, Table student data will also be added or modified


















 

Guess you like

Origin www.cnblogs.com/dosoftwarey/p/11703733.html