捕获mssqlservice 修改表后的数据,统一存储到特定的表中,之后通过代码同步两个库的数据

时间:2023-03-09 19:50:05
捕获mssqlservice 修改表后的数据,统一存储到特定的表中,之后通过代码同步两个库的数据

根据之前的一些想法,如果有A,B 两个数据库, 如果把A 用户通过界面产生的更新或者插入修改,操作的数据同步更新到B 库中,如果允许延时2分钟以内

想法一: 通过创建触发器 把变更的数据和对应的表名称统一存储到某个特定的表,然后通过程序获取转换成sql 更新B数据库中的表,本文主要说明使用该方法

想法二: 通过CDC 记录变更的内容, 园内搜索:  SQL Server 变更数据捕获(CDC)监控表数据  即可 。

以下是测试:

drop  database  T_Mytest

create  database  T_Mytest

 -- 创建修改表
use T_Mytest
create table Mytest
(
id int null ,
name nvarchar (20) null ,
OwndStore int null ) -- 创建记录修改了那个数据库,那张表的记录
create table testdatabaseLog
(
ID int identity not null ,
State int null ,-- 同步状态 0表示初始数据没有同步 ,1 表示已经同步需要插入的文件数据 ChangeTableName nvarchar (25) null , -- 更新了哪个数据库表
createdatetime datetime null ,
ActionType int null , -- 1插入 2更新 3 删除
ActionName nvarchar(20) null ,
Content nvarchar (max) null , -- 更新后的内容
FromStore int null , -- 该数据来自那个门店数据库 标识
ToStore int null , -- 同步到那个门店进行处理
)
go

  

二  创建重要的触发器语句 , 可以应用到所有需要同步的表中,只需要在创建的时候增加触发器即可,

不需要修改里面的内容,只需要修改触发器名称 和应该到哪张表即可

CREATE TRIGGER [dbo].[itrg_triggerTest]  ON [dbo].[Mytest]
after insert , update ,delete
AS
set nocount on
--查询该触发器触发的表
--SELECT @@PROCID, OBJECT_NAME( @@PROCID )
declare @tableName nvarchar(25) ; --宣告变量
DECLARE @D BIT = 0
DECLARE @I BIT = 0 declare @content nvarchar(max) ;
declare @actiontype int ;
declare @actionName nvarchar(15) ;
IF EXISTS(SELECT TOP 1 1 FROM DELETED)
begin
SET @D = 1
end IF EXISTS(SELECT TOP 1 1 FROM INSERTED)
begin
SET @I = 1
end IF @I = 1 AND @D = 0
begin
set @actiontype=1 ;
set @actionName='Insert'
--select N'插入'+'insert into '
select @content= (select * from inserted for xml path)+'' -- select * from inserted for xml path(@tableName),root('insert')
end
else IF @I = 1 AND @D = 1
begin
set @actiontype=2 ;
set @actionName='Update' ;
select @content= (select * from inserted for xml path)+'' ; end
else
begin set @actiontype=3 ;
set @actionName='Delete'
--select N'删除'+'insert into '
select @content= (select * from deleted for xml path)+'' ;
end if ( @content is not null )
begin SELECT @tableName =OBJECT_SCHEMA_NAME( parent_id ) + '.' + OBJECT_NAME( parent_id ) FROM sys.triggers WHERE object_id = @@PROCID insert into testdatabaseLog
(
ChangeTableName ,
createdatetime ,
ActionType ,
ActionName ,
content,FromStore)
values ( @tableName ,GETDATE() , @actiontype, @actionName ,@content, 1) ;
end GO

  

-- 测试数据
insert into Mytest values (1,'苹果',1)
insert into Mytest values (2,'雪梨',1)
insert into Mytest values (3,'香蕉',1)

  

得到结果 测试

捕获mssqlservice 修改表后的数据,统一存储到特定的表中,之后通过代码同步两个库的数据