当触发触发器以响应 INSERT 并且触发器执行另一个 INSERT 语句时使用 @@identity
我有以下表格:
tbl_workshop
id int identity
Name nvarchar(10)
Address nvarchar(40)
tbl_workshop_temp
id int identity
code int
InsUpkey smallint
我有以下语句
insert into tbl_workshop
(Name,Address)
values('x','y')
select @@identity -- My problem is here
我也有以下插入触发器:
create trigger InsertedWorkshop
on tbl_workshop
for insert
as
insert into tbl_workshop_temp
(code,InsUpKey)
select id,1
from inserted
当 select @@identity
语句运行时,我得到 id
中插入行的 id
code>tbl_workshop_temp 而不是插入 tbl_workshop
中的 id
我知道我必须使用 scope_identity
但我无法更改代码。我只能改变我的触发器。 我现在该怎么办?请帮我。
I have following tables:
tbl_workshop
id int identity
Name nvarchar(10)
Address nvarchar(40)
tbl_workshop_temp
id int identity
code int
InsUpkey smallint
And I have follwing statements
insert into tbl_workshop
(Name,Address)
values('x','y')
select @@identity -- My problem is here
And I have following trigger for insert too:
create trigger InsertedWorkshop
on tbl_workshop
for insert
as
insert into tbl_workshop_temp
(code,InsUpKey)
select id,1
from inserted
when the select @@identity
statement runs I get the id
of inserted row in tbl_workshop_temp
instead of id
inserted in tbl_workshop
I know I must use scope_identity
but I can't change the code. I just can change my trigger.
What should I do now? Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能欺骗
@@identity
返回一些不同的值。您可以做的就是从tbl_workshop_temp
中删除IDENTITY
属性,并且该列中没有递增值(只需使用与tbl_workshop
相同的 id >),完全删除该列,或者以这种方式将其填充到触发器中(但这意味着它只适用于一行):使用 SQL Server 2005 及更高版本,您可以变得更聪明 - 您可以更改上面的内容,这样它使用
ROW_NUMBER()
来处理多行,或者您可以使用INSTEAD OF TRIGGER
代替(没有双关语)并简单地更改插入语句的顺序。但对于 SQL Server 2000,您的选择确实很有限......You can't trick
@@identity
to return some different value. What you could do is remove theIDENTITY
property from thetbl_workshop_temp
and either not have an incrementing value in that column (just use the same id astbl_workshop
), remove the column altogether, or populate it in the trigger this way (this means that it will only work for one row, however):With SQL Server 2005 and above you could get more clever - you could change the above such that it used
ROW_NUMBER()
to handle multiple rows, or you could use anINSTEAD OF TRIGGER
instead (no pun intended) and simply change the order of the insert statements. But with SQL Server 2000 your options really are limited...请参阅此问题了解每个身份选择工作。您必须更改初始
INSERT
的代码才能修复此问题。@@identity
始终从会话中获取最后一个 ID,并且由于触发器是同一会话的一部分,因此您必须更改在应用程序中获取 ID 的方式。See this question for how each of the identity selections work. You're going to have to change the the code for the initial
INSERT
in order to fix this one.@@identity
always gets the last id from the session, and since the trigger is part of the same session, you'll have to change the way the ID is picked up in the application.您可以像这样使用 where 子句在插入的行中进行选择
You can select in the inserted row with where clause like this