但是,如果没有返回记录集,我发现这段代码将等到 SQL 代码返回,然后再转到下一个 VBA 语句。当一个命令依赖于另一个命令或者如果您需要在继续之前创建整个数据集时会很方便。
Dim Con As ADODB.Connection
Dim CmdTxt As String
Set Con = New Connection
Con.ConnectionString = ThisWorkbook.GetYourConnectString()
Con.Open
CmdTxt = "EXEC db.schema.StoredProc1 @Param1 = 'Yes'"
ExecuteSql Con, CmdTxt, True, True
CmdTxt = "EXEC db.schema.StoredProc2 @Param1 = 'No'"
ExecuteSql Con, CmdTxt, True, True
MsgBox "Both commands completed sequentially"
ExecuteSql 的代码是:
Public Function ExecuteSql(Con As ADODB.Connection, sql As String, _
Optional StopOnError As Boolean = True, _
Optional WaitUntilDone As Boolean = False) As String
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
With cmd
.CommandType = 1
.CommandText = sql
.ActiveConnection = Con
If WaitUntilDone = True Then
.CommandTimeout = 0 'set timeout to unlimited
.Execute , , adExecuteNoRecords 'no records value speeds up internal code
Else
.Execute
End If
End With
ExecuteSql = ""
Exit Function