问题
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