使用 BizTalk SQL 适配器同步数据
如何使用 BizTalk SQL Adapter 通过调用存储过程来同步数据。
引言
在我的上一篇帖子中,我们使用了 UPDATEGRAM
来同步数据。在本教程中,我们使用触发器来监控源数据库中的操作,并创建一个名为 ACTIONHISTORY 的新表来存储操作,包括操作类型、表名、主键、键值和状态。
BizTalk 服务器通过使用存储过程捕获更新的记录。然后,BizTalk 使用这些参数调用目标存储过程,以更新目标数据库中的记录。
使用代码
首先,我们创建一个触发器来监控操作。这里我们使用 UPDATE
,例如。
Create TRIGGER [dbo].[Tri_Monitor_Customers_Update]
ON [dbo].[Customers]AFTER Update
-- Here is the statement to actually see the text of the trigger.
AS
DECLARE @ActionType varchar(12)
DECLARE @TablePKValue varchar(12)
Set @ActionType=2; --perform to updated action
INSERT INTO [SqlAdapterTest].[dbo].[ActionHistory]
([TableName]
,[ActionType]
,[TablePK]
,[TablePKValue]
,[ActionStatus])
select 'Customers',@ActionType,'CustomerID',CustomerID,'New' from inserted
创建存储过程以提取更新的记录
Create PROCEDURE [dbo].[SP_Action_List_Customer]
-- Add the parameters for the stored procedure here
@Rating as nvarchar(10)
as
declare @ActionType as nvarchar(10)
declare @TableName as nvarchar(10)
declare @TablePk as nvarchar(10)
declare @TablePKValue as nvarchar(10)
declare @ActionID as nvarchar(10)
BEGIN
select top 1 @ActionID=ActionID,@ActionType=ActionType,
@TablePKValue=TablePKValue from ActionHistory where ActionStatus='New'
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.if @ActionID is not null
begin
update ActionHistory set ActionStatus='Used' where ActionID=@ActionID
begin
if @ActionType='1'
SELECT @ActionType as ActionType,
*from dbo.Customers where CustomerID=@TablePKValue for xml auto
end
begin
if @ActionType='2'
SELECT @ActionType as ActionType,
*from dbo.Customers where CustomerID=@TablePKValue for xml auto
end
begin
if @ActionType='0'
SELECT top 1 @ActionType as ActionType,
CustomerID=@TablePKValue from dbo.Customers for xml auto
end
end
else
/* no new customer, return an empty set */
select @ActionType as ActionType,* from Customers where 1 = 0 for xml auto
SET NOCOUNT ON;
END
在目标数据库中,我们同样创建一个存储过程。这里我们以 DELETE
和 INSERT
操作为例。
begin transaction
begin try
if @Action='0' --Delete
BEGIN
delete from Customers where CustomerID=@CustomerID
delete from Interest where Rating=@CustomerID--to delete othertable
END
Else if @Action='1' --Insert
BEGIN
/*BEGIN Interest table*/
IF @Rating IS NOT NULL
begin
DECLARE @TempInterestID int --Check the item
SELECT @TempInterestID = count(1) FROM [Interest] WHERE Rating=@Rating
if @TempInterestID=0
begin
INSERT INTO [Interest](
[Rating],[InterestRate]
)VALUES(
@Rating,@InterestRate
)
end
else
到目前为止,我们已经创建了一个用于捕获和更新数据的过程。与第一部分的上一篇帖子类似,我们应该首先创建一个 BizTalk 项目。涉及的步骤如下:
- 步骤 1:在 Visual Studio 中创建一个 Biztalk 项目
- 步骤 2:使用 SQL Adapter 添加生成的项目
- 步骤 3:映射模式
- 步骤 4:配置编排
- 步骤 5:重新构建并部署项目
- 步骤 6:在 BizTalk Server 2009 管理员控制台中配置应用程序。
以下是步骤的截图
步骤 3. 映射模式
摘要
本教程说明了使用 BizTalk SQL Adapter 在数据库之间进行同步。借助 BizTalk SQL Adapter,我们可以同步 DB 或 ERP 之间的多个表或多个记录,等等。