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

來源:互聯網
上載者:User

測試環境如下:SQL Sever 2000資料庫,遠程主機名稱: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

as

set 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.