我会推荐这种方法:
- 在本地数据库中创建临时表;
- 当您需要同步的表发生变化时,在本地数据库中创建一个触发器;
- 更新暂存表;
-
每隔一段时间将临时表同步到服务器一次(每分钟/小时/天一次,具体取决于您的需求);
A) 在本地数据库中创建链接数据库连接。创建一个过程,将数据从临时表同步到服务器数据库;
B) 或者使用 ASP.NET 同步数据库,读取本地数据库并写入服务器数据库。
此解决方案比直接在 ASP.NET 中执行此操作更好,因为当您的服务器出现可用性问题时,这仍然有效。
一个完整的工作示例:
create table x
( id numeric(18, 0) identity(1,1) not null
, description nvarchar(1000) not null
)
go
create table x_staging
( id numeric(18, 0) not null
, description nvarchar(1000) not null
, synced bit not null default 0
)
go
/*
* create this one on remote server in a database called test
create table remote_table
( id numeric(18, 0) identity(1,1) not null
, source_id numeric(18, 0) not null
, description nvarchar(1000) not null
)
go
*/
create trigger x_ori on x
after insert
as
begin
insert into x_staging
( id
, description
, synced
)
select id
, description
, 0 -- false
from inserted
;
end
go
create procedure sync
as
begin
declare @id numeric(18,0)
declare @description nvarchar(1000)
declare @x_cursor cursor
set @x_cursor = cursor for
select id
, description
from x_staging
open @x_cursor
fetch next
from @x_cursor into @id, @description
while @@fetch_status = 0
begin
insert
into [REMOTE_SERVER].test.dbo.remote_table
( source_id
, description
)
values
( @id
, @description
)
;
update x_staging
set synced = 1
where id = @id
;
fetch next
from @x_cursor into @id, @description
end
close @x_cursor
deallocate @x_cursor
end
go
insert
into x
( description
)
values
( 'test'
)
go
begin
exec sync;
end
Calling sync
将进行同步。请注意创建remote_table
在另一台服务器上并创建数据库链接。