以下では、テーブル "test"に値を挿入し、新しい行の@@identityを正常に取得します。次に、テーブルtest2に(正常に)値を挿入しますが、取得される@@identityは常に「0」です。2番目の@@identityをフェッチすることの何が問題になっていますか?どうすればこれを修正できますか?
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
結果例:INSERT INTO Test3(test_id、test2_id)VALUES( '18'、 '0')