0

下面我在表“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')

4

1 回答 1

1

怎么样:

sql = "INSERT INTO test(data) VALUES ('" & name & "');" & _
      "SELECT NewID = SCOPE_IDENTITY();"
SET rs = cn.Execute (sql)
testIdentity = rs.Fields("NewID")

话虽如此,您至少应该使用参数化语句,或者更好的是存储过程。另外,我不确定为什么在插入数值时要在数值周围加上单引号。您是否将数字存储为字符串?为什么?如果不是,你为什么把它们当作字符串对待?

于 2013-02-11T01:41:18.327 回答