Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @@Identity

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?

like image 726
user2618908 Avatar asked Jul 29 '13 17:07

user2618908


1 Answers

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)
like image 121
HansUp Avatar answered Oct 18 '22 10:10

HansUp