3

In a VBA module for Excel. Using an ADODB.Connection and this connection string:

"Provider=SQLOLEDB;Data Source=MARS;Initial Catalog=automation;Trusted_connection=yes;"

I want to:

  1. INSERT INTO test (data) VALUES ('Something')
  2. Retrieve the auto incremented identity (test.data_id) of the newly inserted row.
Community
  • 1
  • 1
user743094
  • 329
  • 1
  • 6
  • 19

1 Answers1

6
Dim identity as integer
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset

cn.ConnectionString = "whatever..."
cn.Open
cn.Execute ("INSERT INTO test(data) VALUES ('hello world')")
rs.Open "SELECT @@identity AS NewID", cn
identity = rs.Fields("NewID") 
MsgBox (identity)
user743094
  • 329
  • 1
  • 6
  • 19
  • Awesome , thanks just what I was looking for , worked like magic – spacemonkey Oct 14 '16 at 14:46
  • 2
    If you have a connection variable this can be simplified as `identity = cn.Execute("SELECT @@Identity")(0)` without creating a recordset. – Ben Dec 10 '19 at 04:56