我正在使用SQL Server2016。以下是适用于UPDATE和INSERT操作的代码。这意味着在将记录插入或更新到MyDB。[dbo]。[DocumentText]表中之后,相应的记录将插入到[AnotherDB]。[dbo]。[Audit]
但是同一场景不适用于同一表上的DELETE操作。 但是,我确实从MyDB。[dbo]。[DocumentText]表中删除记录时触发了触发器。删除单个记录时,DELETE操作的结果如下:
(影响0行) (受影响的1行)
同时,UPDATE和INSERT操作的结果如下(考虑单个记录):
(受影响的1行) (受影响的1行)
除此表外,此表上没有定义其他触发器...
CREATE TRIGGER [dbo].[TR_DocumentText_UPDATE_INSERT_DELETE]
ON MyDB.[dbo].[DocumentText] AFTER INSERT, DELETE, UPDATE
NOT FOR REPLICATION
AS
BEGIN
;WITH CTE AS (
SELECT ISNULL(ins.DocumentID, del.DocumentID) AS DocumentID,
CASE
WHEN ins.DocumentID IS NOT NULL AND ins.DocumentID = del.DocumentID THEN 'UPDATE'
WHEN ins.DocumentID IS NOT NULL AND del.DocumentID IS NULL THEN 'INSERT'
ELSE 'DELETE' END AS AuditType
FROM inserted ins
FULL OUTER JOIN deleted del
ON ins.DocumentID = del.DocumentID
)
,AUDIT_CTE AS (
SELECT
CTE.DocumentID AS PkId,
'ODRT' AS Code,
CTE.AuditType,
'TSRE' AS MainEntityCode,
doc.OppId AS MainEntityPkId
FROM [MyDB].[dbo].[DocumentText] t WITH (NOLOCK)
INNER JOIN [MyDB].[dbo].[Document] doc WITH (NOLOCK)
ON t.DocumentID = doc.DocumentID
INNER JOIN CTE
ON CTE.DocumentID = t.DocumentID
WHERE doc.OppId IS NOT NULL
)
INSERT [AnotherDB].[dbo].[Audit] (Code, PKID, AuditType, MainEntityCode, MainEntityPKID)
SELECT
Code,
PKID,
AuditType,
MainEntityCode,
MainEntityPkId
FROM AUDIT_CTE;
END
答案 0 :(得分:0)
按照建议的ZLK,我应该从[MyDB]。[dbo]。[DocumentText] t WITH(NOLOCK)中删除,然后直接查询为“ FROM CTE ...”。就是这样。