我有一个更新记录的存储过程。我们的DBA创建了一个触发器,用于更新该行并停用记录。然后它创建一个相同的记录,但有一个活动标志,它会收到一个新的自动生成的PK。所以它是这样的:
PK=1, Active=1, Data='test' --> PK=1, Active=0, Data='test' --> PK=2, Active=1, Data='test2'
但是在我调用更新的存储过程中,我需要获取触发器插入的最后一行。
有可能吗?
这是我的更新代码:
UPDATE [OASIS].[dbo].[TT_PEQHeader]
SET
[LastUpdateDate] = GETDATE()
,[LastUpdateBy] =@intUserPK
,[ID] = @vchID
,[Description] = @vchDescription
,[CompletionRate] = @dcCompletionRate
,[IndustryExperiance] = @intIndustryExperiance
WHERE PEQHeaderPK= @intPEQHeaderPK
SELECT * FROM vw_TT_PEQHeader WHERE PEQHeaderPK = @intPEQHeaderPK
我目前正在根据发送给SP的PK获取记录。这就是我需要改变的地方。
这是触发器代码:
USE [OASIS]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[Update_TT_PEQHeader]
ON [dbo].[TT_PEQHeader]
INSTEAD OF UPDATE
AS
BEGIN
SET NOCOUNT ON;
Declare @dPEQHeaderPK AS INT
Declare @dLastUpdateDate AS DATETIME
Declare @dLastUpdateBy AS INT
Declare @dID AS VARCHAR(25)
Declare @dDescription AS VARCHAR(50)
Declare @dVersion AS INT
Declare @dPreviousVersionPK AS INT
Declare @dActive AS BIT
Declare @dCompletionRate AS DECIMAL(18,2)
Declare @dIndustryExperiance AS INT
Declare @NewPEQHeaderPK AS INT
SELECT
@dPEQHeaderPK =a.PEQHeaderPK,
@dLastUpdateDate = a.LastUpdateDate,
@dLastUpdateBy = a.LastUpdateBy,
@dID = a.ID,
@dDescription = a.Description,
@dVersion = a.Version,
@dPreviousVersionPK = a.PreviousVersionPK,
@dActive = a.Active,
@dCompletionRate = a.CompletionRate,
@dIndustryExperiance = a.IndustryExperiance
FROM INSERTED a
INNER JOIN deleted ON a.PEQHeaderPK = deleted.PEQHeaderPK
/*Deativate the old record*/
Update TT_PEQHeader SET Active = 0 where PEQHeaderPK = @dPEQHeaderPK
IF(@dActive = 1)
BEGIN
/*Copy and paste a new PEQH record*/
INSERT INTO TT_PEQHeader
SELECT GETDATE(),@dLastUpdateBy,GETDATE(),@dLastUpdateBy,@dID,@dDescription,@dVersion + 1,@dPEQHeaderPK,1,@dCompletionRate,@dIndustryExperiance
SELECT @NewPEQHeaderPK = SCOPE_IDENTITY()
/*Copy and paste a new batch of PEQD records*/
INSERT INTO TT_PEQDetail
SELECT GETDATE(),@dLastUpdateBy,GETDATE(),@dLastUpdateBy,@NewPEQHeaderPK,QuestionID,QuestionText FROM TT_PEQDetail WHERE PEQHeaderFK = @dPEQHeaderPK
END
END