下面我在表“test”中插入一个值,并成功检索新行的@@ identity。然后我将一个值插入表test2(成功),但检索到的@@ identity始终为“0”。获取第二个@@身份有什么问题?我该如何解决这个问题?
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')
答案 0 :(得分:1)
怎么样:
sql = "INSERT INTO test(data) VALUES ('" & name & "');" & _
"SELECT NewID = SCOPE_IDENTITY();"
SET rs = cn.Execute (sql)
testIdentity = rs.Fields("NewID")
现在说,你至少应该使用参数化语句,或者更好的是存储过程。此外,我不确定为什么在插入数字值时会在数字值周围加上单引号。您是否将数字存储为字符串?为什么?如果没有,你为什么要把它们当成字符串?