我想从表中检索最新插入的甚至更新的标识。但每当我编写以下代码时,根本就没有结果。
select *
from PersonHowEducation prh
inner join HowzeEducation he on prh.HowzeEducationId = he.HowzeEducationId
where he.HowzeEducationId = @@IDENTITY
我该怎么做?
答案 0 :(得分:1)
如果这是批处理脚本的一部分,并且您刚刚将其插入到同一会话中,那么您将使用SCOPE_IDENTITY()来检索最后插入的HowzeEducationId
值。
select * from PersonHowEducation prh inner join HowzeEducation he on
prh.HowzeEducationId=he.HowzeEducationId
where he.HowzeEducationId=SCOPE_IDENTITY()
但是,如果这是一个完全不同的会话,那个不是 JUST 的会话执行插入,那么你可以使用
来插入最后一条记录select * from PersonHowEducation prh inner join HowzeEducation he on
prh.HowzeEducationId=he.HowzeEducationId
where he.HowzeEducationId=(select top(1) HowzeEducationId from HowzeEducation
order by HowzeEducationId desc)
注意:在极少数情况下,标识插入不会在表中创建最大的id,例如,如果有人认为某个表应该有1条id = 1,000,000,001的记录,手动将身份重新设置为10,001。
另一种替代方案,如果可以在插入后删除记录,则可能会失败。
select * from PersonHowEducation prh inner join HowzeEducation he on
prh.HowzeEducationId=he.HowzeEducationId
where he.HowzeEducationId=(SELECT IDENT_CURRENT('HowzeEducation'))