日期:2014-05-18  浏览次数:20419 次

新增一条记录后返回该记录的id
表中的ID字段是自动增长列,现在我想插入一条记录,但是我想得到插入后,该记录对应的ID,请问这个SQL语句怎么写呀?
为了考虑到多用户并发性,这样写肯定不行,1、insert......values(...)   2、select   @@identity   。这样肯定不行,有没有别的办法呀?

------解决方案--------------------
插入前
select id into #t1 from 表
插入后检索
select id from 表 where id not in (select id from #t1)
为新插入的记录ID
------解决方案--------------------
为何不行?
如果不放心,你就begin tran 一下,从获得insert权后,表就被你锁定,直到commit
------解决方案--------------------
insert into tablename (col1,col2) values (v1,v2);select id from tablename where id=@@identity
其中id为自增的唯一标识字段。这条语句不用分割,在同一次调用中执行
------解决方案--------------------
-- scope_identity(),只在当前作用域内返回值
在insert后,执行select scope_identity(),就可获得该记录对应的ID

------解决方案--------------------
为什么肯定不行呢?我觉得肯定行,我用了好几年了
理论上 select scope_identity() 这个语句更严密一些