簡體   English   中英

VBA Excel中的存儲過程未運行

[英]Stored procedure from VBA Excel not running

我正在從VBA調用PC上的存儲過程,並且工作正常。 在另一台PC和其他用戶中,它不起作用。 雖然只有一個查詢,但它可在兩台PC上使用。

我正在調用存儲過程,如下所示:

Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

' Connection string for accessing MS SQL database
ConnectionString = <Connection details>

' Opens connection to the database
cnn.Open ConnectionString
' Timeout error in seconds for executing the entire query; The stored procedure normally runs for around 20 min
cnn.CommandTimeout = 2400

' Process execution
StrQuery = "exec [00_Main] @date = '01/31/2018' "
rst.Open StrQuery, cnn
rst.Close

我猜測執行存儲過程時出現錯誤消息,但是我不知道如何捕獲它。

我嘗試了以下操作,但沒有任何輸出

' Process execution
StrQuery = "exec [00_Main] @date = '01/31/2018' "
rst.Open StrQuery, cnn
Debug.Print rst.Fields.Count
Debug.Print rst.RecordCount
Debug.Print rst
rst.Close

當我在SQL Management Studio中運行存儲過程時,由於存儲過程只是更新表,因此我只會得到輸出消息。 喜歡:

(29145907 rows affected)
(330527 rows affected)

我還嘗試在此處的鏈接后面添加錯誤信息,但是該過程在運行時沒有給我任何錯誤。 喜歡:

' Process execution
DateSelection = Sheets("STB Check").Range("F1")
'StrQuery = "exec [00_Main] @date = '" & DateSelection & "' "
StrQuery = "exec [00_Main] @date = '01/31/2018' "
rst.Open StrQuery, cnn

Done:
rst.Close
Exit Sub

AdoError:

  Dim errLoop As Error
  Dim strError As String

  i = 1

' Process
 StrTmp = StrTmp & vbCrLf & "VB Error # " & Str(Err.Number)
 StrTmp = StrTmp & vbCrLf & "   Generated by " & Err.Source
 StrTmp = StrTmp & vbCrLf & "   Description  " & Err.Description

' Enumerate Errors collection and display properties of
' each Error object.
 Set Errs1 = cnn.Errors
 For Each errLoop In Errs1
      With errLoop
        StrTmp = StrTmp & vbCrLf & "Error #" & i & ":"
        StrTmp = StrTmp & vbCrLf & "   ADO Error   #" & .Number
        StrTmp = StrTmp & vbCrLf & "   Description  " & .Description
        StrTmp = StrTmp & vbCrLf & "   Source       " & .Source
        i = i + 1
   End With
Next

  MsgBox StrTmp

  ' Clean up Gracefully

  On Error Resume Next
  GoTo Done

有任何想法嗎?

使用適當的參數化,並將日期視為Date ,而不是字符串。

與其直接運行ADODB.RecordsetADODB.Recordset使用ADODB.Command 將命令文本設置為僅存儲過程的名稱,然后將ADODB.Parameter添加到其Parameters集合中,以提供單元格值(在驗證IsDate對於該單元格值返回True之后), 例如在docs.microsoft.com上

Dim theDate As Date
theDate = Sheets("STB Check").Range("F1").Value

Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "[00_Main]"

Dim dateParam As ADODB.Parameter
Set dateParam = cmd.CreateParameter("date", adDate, adParamInput)
dateParam.Value = theDate

cmd.Parameters.Append dateParam

Dim results As ADODB.Recordset
Set results = cmd.Execute

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM