如何借助scope_identity()获取Identity值
我有在 TRIGGER 中实现的scope_identity()。
ALTER TRIGGER TempProcTrig
ON Table_temp2
AFTER insert
AS
BEGIN
declare @TempIdentity int
set @TempIdentity =scope_identity()
insert Table_Temp(TempID)
values(@TempIdentity)
END
当 TRIGGER 被触发时 @TempIdentity 获取 Identity 列字段, 并将该值设置到另一个表中。
但是,在触发 TRIGGER 后,@TempIdentity 总是会变为 NULL。
为什么 TempIdentity 没有获取 Identity 字段?我应该在我的代码中更改什么?
I have scope_identity() that implemented in TRIGGER.
ALTER TRIGGER TempProcTrig
ON Table_temp2
AFTER insert
AS
BEGIN
declare @TempIdentity int
set @TempIdentity =scope_identity()
insert Table_Temp(TempID)
values(@TempIdentity)
END
When TRIGGER is fired @TempIdentity gets Identity column field,
and set this value into another table.
But, always after TRIGGER is fired, @TempIdentity gets NULL.
Why TempIdentity dosen't get Identity field? What should I change in my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个问题:您在编写触发器时假设只插入一行。如果通过一条语句插入多行会发生什么?
触发器中有一个特殊的
inserted
表,其中包含由导致触发器触发的操作插入的所有行。你可以这样使用它:First problem: You're writing your trigger with the assumption that only one row will be inserted. What happens if multiple rows are inserted by a single statement?
There is a special
inserted
table available in triggers that contains all of the rows inserted by the operation that caused the trigger to fire. You could use it this way:顾名思义,此问题的原因是
SCOPE_IDENTITY()
仅返回您调用它的范围中的 id 值。从触发器调用它将会返回触发器中的标识值,即
NULL
因为您没有插入任何行。正如 Joe 建议的那样,使用
inserted
表来获取所需的值,而不是使用此函数。The cause of this issue is that, as the name implies,
SCOPE_IDENTITY()
only returns the id value from the scope that you call it in.Calling it from a trigger will return the identity value from within the trigger, which is
NULL
since you aren't inserting any rows.As Joe suggests, use the
inserted
table to get the values needed instead of this function.