下面我在表“test”中插入一个值并成功检索新行的@@identity。然后我在表 test2 中插入一个值(成功),但检索到的 @@identity 始终为“0”。获取第二个@@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')