oracle触发器将数据插入到另一个服务器的oracle数据库中?

oracle触发器将数据插入到另一个服务器的oracle数据库中?,第1张

oracle触发器数据插入到另一个服务器的oracle数据库中要用dblink实现两台服务器的数据共享。

oracle db_link 和触发器实现不同数据库表的同步

---创建dblink,dblink_test名称,(被同步数据库的a_test)ST10766用户名,ep密码,ass100连接字符串

create public database link dblink_test

connect to ST10766 identified by ep

using 'ass100'

---删除dblink

----drop public database link dblink_test

----建立表

create table a_test (id int,name varchar(20),pass varchar(20))

select * from a_test

insert into a_test (id,name,pass) values (1,'zzn','shanshan')

insert into b_test (id,username,password) values('1','zxl','xiaolan')

----在目的数据库上,测试dblink,查询的是源数据库的表

select * from a_test@dblink_orc10

select * from a_test

----创建触发器

create or replace trigger a_b_test

after insert or update or delete

on a_test

for each row

begin

if deleting then

delete from b_test where id=:old.id

end if

if inserting then

insert into b_test(id,username,password) //b_test表的字段

values(:new.id,:new.name,:new.pass)//a_test表的字段

end if

if updating then

update b_test set username=:new.name,password=:new.pass where id=:old.id

end if

end a_b_test

--即时同步两个表的实例:

--测试环境: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

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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/8022855.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-12
下一篇2023-04-12

发表评论

登录后才能评论

评论列表(0条)

    保存