sql server:我如何获取插入的最后一条记录?

问题描述:

我这样做:sql server:我如何获取插入的最后一条记录?

With rs 
    .AddNew ' create a new record 
    ' add values to each field in the record 
    .Fields("datapath") = dpath 
    .Fields("analysistime") = atime 
    .Fields("reporttime") = rtime 
    .Fields("lastcalib") = lcalib 
    .Fields("analystname") = aname 
    .Fields("reportname") = rname 
    .Fields("batchstate") = bstate 
    .Fields("instrument") = instrument 
    .Update ' stores the new record 
End With 

' get the last id 
Set rs = cn.Execute("SELECT SCOPE_IDENTITY()", , adCmdText) 

,这是不正常。它返回NULL

+0

可能重复[scope_identity()question](http://stackoverflow.com/questions/3526851/scope-identity-question) – 2010-08-19 23:11:32

它不工作,因为你的更新和你的第二个执行是在不同的范围。 您可能希望SELECT IDENT_CURRENT('tablename')

+0

它的一个好点,但我不认为它的权利。我把范围标识放在WITH子句中,并且仍然返回NULL返回 – 2010-08-19 23:13:43

+0

它表示范围函数需要0个参数 – 2010-08-19 23:15:00

+1

不,您的更新被称为它自己的执行。然后你打电话给第二次执行以获得身份。 imho,SCOPE_IDENTITY()在存储过程中最为有用,它必须一次全部发生。 使用“与rs”并不意味着“在这方面做”全部或全部“ – Matthew 2010-08-19 23:15:08

IDENT_CURRENT在单用户环境中很好。

当您更新时,您已经记录在案。

.Update 
lTheNewID = .Fields("ThisTableID") 

lTheNewID将保存新记录的值。

+0

我有多用户 – 2010-08-20 15:31:58

+0

除非你在存储过程中使用它,否则我会避免它。 – JeffO 2010-08-20 17:43:38

+0

我同意Jeff O,正如我的回答中所述。我会考虑使用存储过程来确保所有事务都发生;并且生成的ID是你在找什么。 – Matthew 2010-08-20 22:49:03