Using @@Identity

不想你离开。 提交于 2019-12-22 05:11:31

问题


I'm wondering how I could get the most recently generated autonumber value from a table in another db. Currently I am doing this:

Do Until rsA.EOF
    'Inserts new row here (works)
    Set rs = New ADODB.Recordset 
    rs.Open "SELECT @@Identity" (Connection info)
    SQLcmd = "UPDATE tbl SET col = " & rs("SELECT @@Identity").Value & " 
    (WHERE statement);"
    DoCmd.RunSQL SQLcmd
    rsA.MoveNext
Loop

But its giving col a value of 0 instead of the newly generated autonumber. Any idea why? Or another way to do this?


回答1:


You didn't show the code which does the INSERT into the other database. If you're using the Execute method of an ADO Connection object to do that, run the SELECT @@Identity query from that same connection object ... not a new connection with the same connection string. @@Identity is only usable within the same connection session; otherwise you'll get 0.

And actually you don't even need a recordset to capture that value. If your connection object is named conn, this will return a recordset, but you need not assign it to a recordset object variable. Simply ask for the first item from the returned recordset.

Debug.Print "most recent autonumber: " & _
    conn.Execute("SELECT @@Identity")(0)


来源:https://stackoverflow.com/questions/17930933/using-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!