通過觸發器實現資料庫的即時同步

2021-04-01 23:25:58 字數 1560 閱讀 6099

--即時同步兩個表的例項:

--測試環境:sql2000,遠端主機名:xz,使用者名稱:sa,密碼:無,資料庫名:test

--建立測試表,不能用標識列做主鍵,因為不能進行正常更新

--在本機上建立測試表,遠端主機上也要做同樣的建表操作,只是不寫觸發器

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--建立同步的觸發器

create trigger t_test on test

for insert,update,delete

asset  xact_abort on

--啟動遠端伺服器的msdtc服務

exec master..xp_cmdshell 'isql /s"xz" /u"sa" /p"" /q"exec master..xp_cmdshell ''net start msdtc'',no_output"',no_output

--啟動本機的msdtc服務

exec master..xp_cmdshell 'net start msdtc',no_output

--進行分布事務處理,如果錶用標識列做主鍵,用下面的方法

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--插入資料測試

insert into test

select 1,'aa'

union all select 2,'bb'

union all select 3,'c'

union all select 4,'dd'

union all select 5,'ab'

union all select 6,'bc'

union all select 7,'ddd'

--刪除資料測試

delete from test where id in(1,4,6)

--更新資料測試

update test set name=name+'_123' where id in(3,5)

--顯示測試的結果

select * from test a full join

openrowset('sqloledb','xz';'sa';'',test.dbo.test) b on a.id=b.id

通過觸發器實現資料庫的即時同步

即時同步兩個表的例項 測試環境 sql2000,遠端主機名 xz,使用者名稱 sa,密碼 無,資料庫名 test 建立測試表,不能用標識列做主鍵,因為不能進行正常更新 在本機上建立測試表,遠端主機上也要做同樣的建表操作,只是不寫觸發器 if exists select from dbo.sysobj...

通過觸發器實現資料庫的即時同步

即時同步兩個表的例項 測試環境 sql2000,遠端主機名 xz,使用者名稱 sa,密碼 無,資料庫名 test 建立測試表,不能用標識列做主鍵,因為不能進行正常更新 在本機上建立測試表,遠端主機上也要做同樣的建表操作,只是不寫觸發器 if exists select from dbo.sysobj...

通過觸發器實現資料庫的即時同步

即時同步兩個表的例項 測試環境 sql2000,遠端主機名 xz,使用者名稱 sa,密碼 無,資料庫名 test 建立測試表,不能用標識列做主鍵,因為不能進行正常更新 在本機上建立測試表,遠端主機上也要做同樣的建表操作,只是不寫觸發器 if exists select from dbo.sysobj...