Below I Insert a value into table "test" and retrieve the @@identity of the new row successfully. Then I insert a value into table test2 (successfully), but the @@identity retrieved is "0" always. What's going wrong with fetching the 2nd @@identity? How can I fix this?
Sub GoDo()
Dim testIdentity As Integer
Dim test2Indentity As Integer
Dim name As String
Dim concept As String
name = Cells(1, 1)
concept = Cells(1, 2)
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim rs2 As New ADODB.Recordset
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=MARS;Initial Catalog=automation;Trusted_connection=yes;"
cn.Open
cn.Execute ("INSERT INTO test(data) VALUES ('" & name & "')")
rs.Open "SELECT @@identity AS NewID", cn
testIdentity = rs.Fields("NewID")
rs.Close
cn.Execute ("INSERT INTO test2(data) VALUES ('" & concept & "')")
rs2.Open "SELECT @@identity AS NewID", cn
testIdentity = rs2.Fields("NewID")
rs2.Close
cn.Execute ("INSERT INTO test3(test_id, test2_id) VALUES ('" & testIdentity & "','" & test2Indentity & "')")
cn.Close
End Sub
Result e.g.: INSERT INTO Test3 (test_id, test2_id) VALUES ('18','0')