提问人:Suraj 提问时间:11/9/2023 最后编辑:Suraj 更新时间:11/9/2023 访问量:68
在源表上插入、更新、删除的触发器
Trigger for Insert, Update, Delete on source table
问:
我想将一个表上的(插入/更新/删除)等更改复制到不同架构中的另一个表上 我想在源到目标表的每个插入、更新和删除上创建触发器
我能够复制插入和删除,但更新没有复制?
下面是插入、更新和删除的触发代码
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
插入和删除按预期工作,但更新未更新新值
除了创建触发器之外,还有没有更好的复制方法
答: 暂无答案
评论
set identity_insert on/off
是一种代码味。应用程序代码永远不应该尝试这样做,因为identity_insert一次只能为一个表(每个数据库)打开。FROM deleted as u inner join customer.customerEmail on customer.customerEmail.Id=u.Id where customer.customerEmail.Id=(select u.Id from deleted u)