In VBA, I am trying to use an ADO recordset and a connection to perform separate operations on a SQL Server #TEMP table.
I would think that in the code below the recordset and the connection are using the same session/scope, and therefore the #TEMP table could be accessed using either object. This does not appear to be the case. The recordset appears to see the #TEMP table created by the connection, but the connection doesn't appear to see the records inserted by the recordset. And the recordset returns no records after the attempted deletion by the connection object.
I am wondering why this is, and how I can do it right.
EDIT: The code below fails whether I use a local #TEMP table or a global ##TEMP table.
Dim cn As New adodb.Connection
Dim rst As New adodb.Recordset
'Open Connection.
cn.Open cConnSeasFcst
'Create temp table.
cn.Execute "CREATE TABLE #TEMP (COL1 INT)"
'Open rst.
With rst
.ActiveConnection = cn
.CursorLocation = adUseClient
.CursorType = adOpenDynamic
.LockType = adLockBatchOptimistic
End With
'Add records to temp table using rst.
rst.Open "#TEMP"
For i = 1 To 5
rst.AddNew
rst!COL1 = i
rst.Update
Next
'Delete records using connection.
cn.Execute "DELETE #TEMP WHERE COL1 IN(2,4)", raff
'Display.
rst.Requery
While Not rst.EOF ' ##ALWAYS AT EOF. RECORDS ARE NOT RETURNED.##
Debug.Print rst!COL1
rst.MoveNext
Wend
The final recordset requery does not return any records at all, and the raff
variable is zero -- it appears to me that the connection object can't see any of the records inserted by the recordset.