我有 2 个表,Contact 和 ContactFunction。它们具有一对多关系,因为在一个联系人中可以有多个 ContactFunction。所以 ContactFunction 有 ContactID 作为外键。因此,在我的 .NetCore Web 应用程序中,我可以在同一页面上更新联系人及其功能。但这实际上是在保存上面提到的两个单独的实体。我在联系人表上有一个触发器,它将插入/更新/删除放入历史表中。我还需要一种方法来在此触发器中包含任何 ContactFunction 更改。但是在这个阶段,由于我假设的关系,似乎还没有提交到 ContactFunction 表。除了为两者创建历史表之外,您能想出一种方法吗?
我正在尝试从 Contact 表触发器中的 ContactFunction 表中读取数据,但它还不存在。变量@FUNCTIONSSTRING 是我试图从第二个表(ContactFunction)中读取数据的地方
USE [DI_Business_IE_EF_Development04]
GO
/****** Object: Trigger [dbo].[ContactHistoryLog] Script Date: 25/01/2019 09:33:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[ContactHistoryLog] ON [dbo].[Contact]
AFTER INSERT,UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @CurrentDateTime datetime2 = SYSUTCDATETIME();
DECLARE @Action varchar(10);
DECLARE @CONTACTID INT;
DECLARE @FIRSTUPDATE INT;
DECLARE @FUNCTIONSSTRING VARCHAR(250) = '';
DECLARE @INSERTEDID INT;
IF EXISTS (SELECT 1 FROM inserted)
BEGIN
IF EXISTS (SELECT 1 FROM deleted)
BEGIN
SET @Action = 'UPDATE'
END
ELSE
BEGIN
SET @Action = 'INSERT'
END
END
ELSE
BEGIN
SET @Action = 'DELETE'
END
/* Update start times for newly updated data */
UPDATE c
SET
StartDate = @CurrentDateTime, @CONTACTID = c.ID
FROM
dbo.Contact c
INNER JOIN inserted i
ON c.Id = i.Id
SELECT @FIRSTUPDATE = COUNT(*) FROM dbo.ContactHistory WHERE ContactId = @CONTACTID
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
@FUNCTIONSSTRING = @FUNCTIONSSTRING + F.Name + ','
FROM ContactFunction CF
JOIN [Function] F ON F.ID = CF.FunctionID
WHERE CF.ContactID = @CONTACTID
INSERT INTO DBO.ContactHistory(
ContactId,
CompanyID,
Title,
Forename,
Surname,
JobTitle,
ExecutiveNumber,
IsInformationProvider,
Email,
UpdatedBy,
StartDate,
EndDate,
[Action],
FunctionNames
)
SELECT
I.Id,
I.CompanyID,
I.Title,
I.Forename,
I.Surname,
I.JobTitle,
I.ExecutiveNumber,
I.IsInformationProvider,
I.Email,
I.UpdatedBy,
@CurrentDateTime,
@CurrentDateTime,
@Action,
(SELECT SUBSTRING(@FUNCTIONSSTRING, 0, LEN(@FUNCTIONSSTRING)))AS FunctionNames
FROM
dbo.Contact c
RIGHT JOIN inserted I
ON c.Id = I.Id
-- if this is first update insert deleted value as well as inserted value, else just put in inserted
IF (@FIRSTUPDATE = 0)
BEGIN
INSERT INTO DBO.ContactHistory(
ContactId,
CompanyID,
Title,
Forename,
Surname,
JobTitle,
ExecutiveNumber,
IsInformationProvider,
Email,
UpdatedBy,
StartDate,
EndDate,
[Action],
FunctionNames
)
SELECT
d.Id,
d.CompanyID,
d.Title,
d.Forename,
d.Surname,
d.JobTitle,
d.ExecutiveNumber,
d.IsInformationProvider,
d.Email,
d.UpdatedBy,
d.StartDate,
ISNULL(d.StartDate,@CurrentDateTime),
'NONE',
(SELECT SUBSTRING(@FUNCTIONSSTRING, 0, LEN(@FUNCTIONSSTRING)))AS FunctionNames
FROM
dbo.Contact c
RIGHT JOIN deleted d
ON c.Id = d.Id
END
END
我希望看到 ContactFunction 表的最新更改,但它不存在。有没有办法做到这一点?