I have an access vba code which runs a query in SQL Server 14.0. However it gets about 20 minutes through before just stopping the query and moving onto the next line of my vba code.
If I copy the code directly into SQL and run it there it runs properly with no issues. I originally thought this was due to either a connection or command timeout, however usually this should have generated an error message (and even so I have set the timeouts to 0 to force them to run indefinitely).
Please find my code below, it uses a Cursor to loop through a range of tables to complete the same task. This task involves looping through a Do While until the conditions are met. At this point the loop should finish and start on the next table.
It does complete 3 of the cursor loops, but then it starts the next one and then just stops.
Hopefully the code makes sense, it is quite lengthy in access and I have had to split it all up using line breaks to make my SQL string easier to decipher and (attempt) to debug.
''...Declare all relevant variables above...
On Error GoTo 0
SQL_STR1 = "DECLARE @STRSQL AS Varchar(max) " & vbCrLf & _
"DECLARE @TableName VARCHAR(50) " & vbCrLf & _
"DECLARE LoopVal CURSOR FOR SELECT TableName_ FROM [DBASE_NAME].[dbo].[a_Base_Year_Matrices] " & vbCrLf & _
"OPEN LoopVal " & vbCrLf & _
"FETCH NEXT FROM LoopVal INTO @TableName " & vbCrLf & _
"WHILE @@FETCH_STATUS = 0 " & vbCrLf & _
"BEGIN " & vbCrLf & _
SQL_STR2 = "SET @STRSQL = "
'...Create Some Tables...
"WHILE (@COUNTT < 1959 AND @COUNTTER < 150)" & vbCrLf & _
"BEGIN" & vbCrLf & _
'...Runs loops to meet conditions, once met drop unneeded tables and create final output...
SQL_STR3 = "EXEC(@STRSQL) " & vbCrLf & _
"FETCH NEXT FROM LoopVal INTO @TableName " & vbCrLf & _
"END " & vbCrLf & _
"CLOSE LoopVal " & vbCrLf & _
"DEALLOCATE LoopVal "
SQL_ALL = SQL_STR1 + SQL_STR2 + SQL_STR3
Set cnn = New ADODB.Connection
Set rs = New ADODB.Recordset
'Set SQL Server Location
cnn.ConnectionTimeout = 0
cnn.Open "Driver={SQL Server};Server=" & ServerName & ";Trusted_Connection=Yes;"
Set rs.ActiveConnection = cnn
DoCmd.SetWarnings False
cnn.CommandTimeout = 0
''Code to check to paste directly into SQL
''Debug.Print SQL_ALL
rs.Open SQL_ALL, cnn, adOpenForwardOnly
Next b
Next a
End Sub
{SQL Server}is ancient, it's the default driver that came with Windows 98. While it has been updated a bit, it's no longer supported for new development. You can download a new one here