Using a VBA script in Excel, I am trying to insert a new row into a table and then return the id value of that row. If I run:
INSERT INTO DataSheet(databaseUserID, currentTimestamp) VALUES (1, CURRENT_TIMESTAMP); SELECT SCOPE_IDENTITY()
in Management Studio, a row is inserted and returns the expected value of the identifier. However, when I run the same query through the ADODB recordset in VBA, I have problems. The row is indeed inserted, but I cannot access the identifier value. The recordset contains 0 fields and is actually closed. I tried with and without a semicolon, and I also tried to run the query as a single transaction. Same thing, no dice. Any idea what is going on?
Here is my VBA:
Dim rs As ADODB.Recordset Dim cn As Connection Dim SQLStr As String Dim serverName As String Dim databaseName As String serverName = "MSSQLServer" databaseName = "QA" cxnStr = "Driver={SQL Server};Server=" & serverName & ";Database=" & databaseName & ";" SQLStr = "INSERT INTO DataSheet(databaseUserID, currentTimestamp) VALUES (1, CURRENT_TIMESTAMP); SELECT SCOPE_IDENTITY()" Set cn = New ADODB.Connection cn.Open cxnStr Set rs = New ADODB.Recordset rs.Open SQLStr, cn, adOpenKeyset, adLockOptimistic MsgBox (rs.Fields(0).Value)
And the message box is not displayed because rs.Fields(0).Value returns NULL. I added the clock to rs and, as I said, shows 0 fields after the request and also seems to be closed (state = 0).
excel-vba sql-server-2008 adodb recordset
Joecool
source share