Not all SQL commands run when running from VBA

gstyhher  于 2023-02-28  发布在  其他
关注(0)|答案(1)|浏览(94)

Trying to run SQL Server 2017 stored procedures from MS Access 365. The first 3 SP run, then nothing. Executing them from SQL Server works fine

With CurrentDb.QueryDefs("STOREDPROC")
   .SQL = "EXEC dbo.sp_Step1"
   .SQL = "EXEC dbo.sp_Step2"
   .SQL = "EXEC dbo.sp_Step3"
   .SQL = "EXEC dbo.sp_Step4"
   .SQL = "EXEC dbo.sp_Step5"
   .SQL = "EXEC dbo.sp_Step6"
   .ReturnsRecords = False
   .Execute
End With

MsgBox ("Import Complete")
e4yzc0pl

e4yzc0pl1#

As Access PassThrough query STOREDPROC can execute only one SQL instruction, you cannot execute at the same time those stored procedures.

You could use a loop like this:

Sub ExecManySPs()
  Dim i As Long
  
  With CurrentDb.QueryDefs("STOREDPROC")
  
    .ReturnsRecords = False
    
    For i = 1 To 6
      .SQL = "EXEC dbo.sp_Step" & i
      .Execute
    Next
  End With

  MsgBox ("Import Complete")
End Sub

Or if you have rights to create stored prodecure, you can create an All-In-One SP, then call it.

Sub ExecManySPsAllIn1()
  With CurrentDb.QueryDefs("qrySqsUpdTmp")
  
    .ReturnsRecords = False
      
    .SQL = "CREATE PROCEDURE [dbo].[sp_StepAllIn1]" & vbCrLf _
       & " AS" & vbCrLf _
       & " BEGIN" & vbCrLf _
       & "    EXEC dbo.sp_Step1;" & vbCrLf _
       & "    EXEC dbo.sp_Step2;" & vbCrLf _
       & "    EXEC dbo.sp_Step3;" & vbCrLf _
       & "    EXEC dbo.sp_Step4;" & vbCrLf _
       & "    EXEC dbo.sp_Step5;" & vbCrLf _
       & "    EXEC dbo.sp_Step6;" & vbCrLf _
       & "END" & vbCrLf
    .Execute
  
    .SQL = "EXEC [dbo].[sp_StepAllIn1]"
    .Execute
  
  End With

  MsgBox ("Import Complete")
End Sub

相关问题