使用 INSERT 中的值插入触发器后

After Insert Trigger using the values from the INSERT

我有以下查询:

INSERT INTO LOAN (MemberSSN, VolumeID, LoanDate) 
OUTPUT inserted.MemberSSN, inserted.VolumeID, inserted.LoanDate 
VALUES ('488-40-', 2, GETUTCDATE())

我想要一个触发器,在 LOAN table 中插入时执行以下查询 - 插入 VOLUME_VOLUME_STATUS table:

INSERT INTO VOLUME_VOLUME_STATUS (VolumeID, StatusID, DateCreated) 
VALUES (>>previouslyInsertedVolumeID<<, 2, getutcdate())

如您所见,我不确定如何告诉 SQL 刚刚插入的 VolumeID,即 2

下面是我写的触发器:

CREATE TRIGGER LoanStatusUpdate_OnLoaning
AFTER INSERT
ON LOAN
BEGIN
    INSERT INTO VOLUME_VOLUME_STATUS (VolumeID, StatusID, DateCreated) 
    VALUES (>>previouslyInsertedVolumeID<<, 2, getutcdate())
END

因此,应该将什么作为 VolumeID 列的值传递,以便参数是激活触发器之前来自 INSERT 的参数?

找出上一个触发器中的一些错误。这是修复了语法错误的那个:

CREATE TRIGGER LoanStatusUpdate_OnLoaning
ON LOAN
AFTER INSERT
AS
    INSERT INTO VOLUME_VOLUME_STATUS (VolumeID, StatusID, DateCreated) 
    VALUES (New.VolumeID, 2, getutcdate())
GO

我想你只想使用 inserted:

CREATE TRIGGER LoanStatusUpdate_OnLoaning ON LOAN AFTER INSERT
BEGIN
    INSERT INTO VOLUME_VOLUME_STATUS (VolumeID, StatusID, DateCreated) 
        SELECT i.VolumeId, 2, getutcdate()
        FROM inserted i;
END;

您也可以从 inserted 中提取 StatusId。并且 DateCreated 可以设置为 VOLUME_VOLUME_STATUS 中的默认值。