在 Microsoft SQL 服务器上插入触发器后 -- 更新新创建记录中的列
After Insert Trigger on Microsoft SQL Server -- Updating a column in a newly created record
我有 3 tables 数据 table、LookUp_1、LookUp_2 都包含 列id 是主键列。 score1_id 和 score2_id 列是外键列。 score1_id 与 LookUp_1 中的 id 链接,score2_id 与 LookUp_2 中的 id 链接。
我的问题是:
我需要创建一个 after insert 触发器,它将计算列从 null 更新为特定的 number/value。只有在数据 table 中插入新记录时才会发生这种情况,并且它只会影响新创建的记录。因此,对于我的示例,id 1 是新插入的记录,现在触发器应该继续并使用 calculation column score1_id 和 score2_id。所以它应该进入 LookUp1 和 LookUp2 并检查每个 id 的权重。例如:3=7 和 2=3。因此在触发器完成后,记录应该更新为计算列 = 21(因为我们正在乘以权重)
所以更新后的 table 记录应该如下所示:
关于如何解决这个问题有什么建议吗??或者任何人想到的一些例子?
非常感谢!
这是你的触发器(你需要完成它)
现在需要更新您发布的列名。
CREATE TRIGGER [triggername]
ON [data]
AFTER
INSERT
AS
BEGIN
declare @v1 int = (Select weight from lookup1 where id=inserted.scoreid1
,@v2 int = (Select weight from lookup2 where id=inserted.scoreid2)
update data
set calculation = @v1*@v2
where inserted.id = data.id
END
或多次插入:
CREATE TRIGGER [triggername]
ON [data]
AFTER
INSERT
AS
BEGIN
update data
set calculation = l1.weight*l2.weight
from data d
join lookup_1 l1 on d.scoreID1=l1.id
join lookup_2 l2 on d.scoreid2=l2.id
join inserted on inserted.id = d.id
END
我有 3 tables 数据 table、LookUp_1、LookUp_2 都包含 列id 是主键列。 score1_id 和 score2_id 列是外键列。 score1_id 与 LookUp_1 中的 id 链接,score2_id 与 LookUp_2 中的 id 链接。
我的问题是: 我需要创建一个 after insert 触发器,它将计算列从 null 更新为特定的 number/value。只有在数据 table 中插入新记录时才会发生这种情况,并且它只会影响新创建的记录。因此,对于我的示例,id 1 是新插入的记录,现在触发器应该继续并使用 calculation column score1_id 和 score2_id。所以它应该进入 LookUp1 和 LookUp2 并检查每个 id 的权重。例如:3=7 和 2=3。因此在触发器完成后,记录应该更新为计算列 = 21(因为我们正在乘以权重)
所以更新后的 table 记录应该如下所示:
关于如何解决这个问题有什么建议吗??或者任何人想到的一些例子?
非常感谢!
这是你的触发器(你需要完成它)
现在需要更新您发布的列名。
CREATE TRIGGER [triggername]
ON [data]
AFTER
INSERT
AS
BEGIN
declare @v1 int = (Select weight from lookup1 where id=inserted.scoreid1
,@v2 int = (Select weight from lookup2 where id=inserted.scoreid2)
update data
set calculation = @v1*@v2
where inserted.id = data.id
END
或多次插入:
CREATE TRIGGER [triggername]
ON [data]
AFTER
INSERT
AS
BEGIN
update data
set calculation = l1.weight*l2.weight
from data d
join lookup_1 l1 on d.scoreID1=l1.id
join lookup_2 l2 on d.scoreid2=l2.id
join inserted on inserted.id = d.id
END