在源表上插入、更新、删除的触发器

Trigger for Insert, Update, Delete on source table

提问人:Suraj 提问时间:11/9/2023 最后编辑:Suraj 更新时间:11/9/2023 访问量:68

问:

我想将一个表上的(插入/更新/删除)等更改复制到不同架构中的另一个表上 我想在源到目标表的每个插入、更新和删除上创建触发器

我能够复制插入和删除,但更新没有复制?

下面是插入、更新和删除的触发代码

CREATE TRIGGER dbo.trgContactEmail ON dbo.ContactEmail
AFTER INSERT, UPDATE, DELETE
AS
IF EXISTS ( SELECT 0 FROM Deleted )
BEGIN
   IF EXISTS ( SELECT 0 FROM Inserted )
   BEGIN
      Set identity_insert customer.CustomerEmail on
      update customer.customerEmail set
      --Id=u.Id,
      CreatedOn=u.CreatedOn,
      CreatedBy=u.CreatedBy,
      LastUpdatedBy=u.LastUpdatedBy,
      LastUpdatedOn=u.LastUpdatedOn,
      CustomerID=u.ContactId,
      CodeId_EmailType=u.CodeId_EmailType,
      EmailAddress=u.EmailAddress,
      DomainId=u.DomainId
      --SELECT  u.Id,u.CreatedOn,u.CreatedBy,u.LastUpdatedBy,u.LastUpdatedOn,u.ContactId,u.CodeId_EmailType,u.EmailAddress,u.DomainId
      FROM inserted as u inner join customer.customerEmail
      on customer.customerEmail.Id=u.Id 
      where customer.customerEmail.Id=(select u.Id from inserted u)
      Set identity_insert customer.CustomerEmail off
   END
ELSE
   BEGIN
      delete from customer.CustomerEmail 
      --(Id,CreatedOn,CreatedBy,LastUpdatedBy,LastUpdatedOn,CustomerID,CodeId_EmailType,EmailAddress,DomainId)
      where CustomerID=(select d.ContactId from deleted as d)
   END
   END
ELSE
   BEGIN
      Set identity_insert customer.CustomerEmail on
      insert into customer.CustomerEmail (Id,CreatedOn,CreatedBy,LastUpdatedBy,LastUpdatedOn,CustomerID,CodeId_EmailType,EmailAddress,DomainId)
      SELECT  i.Id,i.CreatedOn,i.CreatedBy,i.LastUpdatedBy,i.LastUpdatedOn,i.ContactId,i.CodeId_EmailType,i.EmailAddress,i.DomainId
      FROM inserted as i
      Set identity_insert customer.CustomerEmail off
   END   
GO

插入和删除按预期工作,但更新未更新新值

除了创建触发器之外,还有没有更好的复制方法

Server T-SQL 触发器

评论

0赞 Dale K 11/9/2023
调试它?看起来它应该有效。
2赞 AlwaysLearning 11/9/2023
set identity_insert on/off是一种代码味。应用程序代码永远不应该尝试这样做,因为identity_insert一次只能为一个表(每个数据库)打开。
1赞 Mitch Wheat 11/9/2023
SQL Server 提供了两个跟踪数据更改的功能:更改数据捕获和更改跟踪。
0赞 seanb 11/9/2023
这似乎是重复的: - 你真的不需要 WHERE 子句,因为 join 强制执行它,不是吗?FROM deleted as u inner join customer.customerEmail on customer.customerEmail.Id=u.Id where customer.customerEmail.Id=(select u.Id from deleted u)
1赞 Zohar Peled 11/9/2023
顺便说一句:你真的应该在这里使用三种不同的触发器。这将使代码更简单,更易于调试和维护。此外,如果使用的是 SQL Server 2016 或更高版本,则可能不应使用触发器执行此操作,而应仅使用时态表。历史记录表可以在不同的架构上手动定义 - learn.microsoft.com/en-us/sql/relational-databases/tables/...

答: 暂无答案