--即時同步兩個表的實例:
--測試環(huán)境:SQL2000,遠程主機名:xz,用戶名:sa,密碼:無,數(shù)據(jù)庫名:test
--創(chuàng)建測試表,不能用標(biāo)識列做主鍵,因為不能進行正常更新
--在本機上創(chuàng)建測試表,遠程主機上也要做同樣的建表操作,只是不寫觸發(fā)器
if exists (select * from dbo.sysobjects where id = object_id(N‘[test]‘) and OBJECTPROPERTY(id, N‘IsUserTable‘) = 1)
drop table [test]
create table test(id int not null constraint PK_test primary key
,name varchar(10))
go
--創(chuàng)建同步的觸發(fā)器
create trigger t_test on test
for insert,update,delete
as
set XACT_ABORT on
--啟動遠程服務(wù)器的MSDTC服務(wù)
exec master..xp_cmdshell ‘isql /S"xz" /U"sa" /P"" /q"exec master..xp_cmdshell ‘‘net start msdtc‘‘,no_output"‘,no_output
--啟動本機的MSDTC服務(wù)
exec master..xp_cmdshell ‘net start msdtc‘,no_output
--進行分布事務(wù)處理,如果表用標(biāo)識列做主鍵,用下面的方法
BEGIN DISTRIBUTED TRANSACTION
delete from openrowset(‘sqloledb‘,‘xz‘;‘sa‘;‘‘,test.dbo.test)
where id in(select id from deleted)
insert into openrowset(‘sqloledb‘,‘xz‘;‘sa‘;‘‘,test.dbo.test)
select * from inserted
commit tran
go
--插入數(shù)據(jù)測試
insert into test
select 1,‘a(chǎn)a‘
union all select 2,‘bb‘
union all select 3,‘c‘
union all select 4,‘dd‘
union all select 5,‘a(chǎn)b‘
union all select 6,‘bc‘
union all select 7,‘ddd‘
--刪除數(shù)據(jù)測試
delete from test where id in(1,4,6)
--更新數(shù)據(jù)測試
update test set name=name+‘_123‘ where id in(3,5)
--顯示測試的結(jié)果
select * from test a full join
openrowset(‘sqloledb‘,‘xz‘;‘sa‘;‘‘,test.dbo.test) b on a.id=b.id