How to get the insert ID from this ADODB.Recordset?

sholsinger picture sholsinger · Mar 31, 2011 · Viewed 19.9k times · Source

I'm trying to avoid using straight SQL queries in my web app. I looked around and have come to the conclusion that ADO Recordsets would be the best or at least safest tool for the job. I need to insert records into a database table. Unfortunately I'm at a loss as to how to get the identity value for the record which was just inserted. Here's a reduction of what I've got now:

<%
dim insertID, rs
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "my_table_name", conn, adOpenForwardOnly, adLockOptimistic

rs.AddNew()

Call m_map_values_to_rs(rs)

rs.Update()

insertID = rs("id")

rs.Close()
rs = Nothing
%>

The code I have is successfully inserting the record, but I can't for the life of me figure out how to get the id field of the Recordset to update after the insert. How can I get the identity column value back from this Recordset?

UPDATE - Here's the solution with regard to the code above.

I had to change the cursor type to adOpenKeyset instead of adOpenForwardOnly. After I did this the record is automatically updated with the "auto number" field's new value after the insert. However it is not what you think it is. The value of rs("id") doesn't become an integer or even a variant. It becomes some sort of Automation type and cannot be evaluated as a number. Nor can CInt() be used directly on that type for some reason. So what you must do is to convert the value to a string and then convert it to an Int. Here's how I managed that:

insertID = CInt( rs("id") & "" )

Thanks to Dee for their answer. It helped immensely.

Answer

Dee picture Dee · Mar 31, 2011

This article explains the means of getting identity value with example code.

The relevant code snippet is:

<% 
    fakeValue = 5 
    set conn = CreateObject("ADODB.Connection") 
    conn.open "<conn string>" 
    sql = "INSERT someTable(IntColumn) values(" & fakeValue & ")" & _ 
        VBCrLf & " SELECT @@IDENTITY" 
    set rs = conn.execute(sql) 
    response.write "New ID was " & rs(0) 
    rs.close: set rs = nothing 
    conn.close: set conn = nothing 
%>