问题如何通过触发器实现数据库的即时同步?
解答具体的解决方法请参考下文
即时同步两个表的示例如下:
测试环境如下:SQL Sever 数据库远程主机名:xz用户名:sa密码:无数据库名:test
创建测试表请注意不能用标识列做主键因为不能进行正常的更新
然后在本机上创建测试表注意远程主机上也要做同样的建表操作只是不写触发器
if exists (select * from dbosysobjects where id = object_id(N[test]) and OBJECTPROPERTY(id NIsUserTable) = )
drop table [test]
create table test(id int not null constraint PK_test primary key
name varchar())
go
创建同步的触发器
create trigger t_test on test
for insertupdatedelete
as
set XACT_ABORT on
启动远程服务器的MSDTC服务
exec masterxp_cmdshell isql /Sxz /Usa /P /qexec masterxp_cmdshell net start msdtcno_outputno_output
启动本机的MSDTC服务
exec masterxp_cmdshell net start msdtcno_output
进行分布事务处理假如表用标识列做主键你可以使用下面的这个方法
BEGIN DISTRIBUTED TRANSACTION
delete from openrowset(sqloledbxz;sa;testdbotest)
where id in(select id from deleted)
insert into openrowset(sqloledbxz;sa;testdbotest)
select * from inserted
commit tran
go
插入数据测试
insert into test
select aa
union all select bb
union all select c
union all select dd
union all select ab
union all select bc
union all select ddd
删除数据测试
delete from test where id in()
更新数据测试
update test set name=name+_ where id in()
最后显示测试的结果
select * from test a full join
openrowset(sqloledbxz;sa;testdbotest) b on aid=bid