我有2个表Contact和ContactFunction。它们具有一对多关系,因为在Contact中可以具有许多ContactFunction。因此ContactFunction将ContactID作为外键。因此,在我的.NetCore Web应用程序中,我可以在同一页面上更新联系人及其功能。但这实际上是在保存上面提到的两个单独的实体。我在Contact表上有一个触发器,该触发器将插入/更新/删除插入到历史表中。我还需要一种在此触发器中也包含所有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表的最新更改,但是它不存在。有办法吗?