[英]Excel VBA Code to check if a stored procedure exists on SQL Server 2014
我正在編寫一個調用SQL存儲過程的Excel VBA宏。 我想在VBA中編寫代碼來測試該存儲過程是否存在。 我的代碼如下:
Public Function Import_StoredProcedure_Results(usp As ADODB.Command, _
ExecRun_UID As String, _
Scenario As Integer, _
OutputSheet As String, _
uspSPName As String) As Boolean
Dim rs As New ADODB.Recordset
Import_StoredProcedure_Results = False
On Error GoTo ErrorHandler
With usp
.Parameters("@ID").Value = "{" & Run_UID & "}"
.Parameters("@RunType").Value = RunType
Set rs = .Execute
End With
'Write results to Output sheet
If rs.RecordCount <> 0 Then
i = 0
'Copy in the header row
For Each fld In rs.Fields
Sheets(OutputSheet).Range("A1").Cells(1, 1).Offset(0, i).Value = fld.Name
i = i + 1
Next fld
'Copy in the data
Sheets(OutputSheet).Range("A1").Cells(1, 1).Offset(1, 0).CopyFromRecordset rs
End If
Import_StoredProcedure_Results = True
rs.Close
Exit Function
ErrorHandler:
MsgBox Err.Description & " " & "Error - Import_StoredProcedure_Results: " & uspSPName
End Function
嘗試執行該行時,代碼進入錯誤處理程序
.Parameters("@ID").Value = "{" & Run_UID & "}"
然后,一條錯誤消息從SQL傳回,說給定的存儲過程不存在。 我想在調用此VBA函數之前發現此存儲過程是否存在。 這樣,它將更加模塊化。 這個怎么做?
information_schema.routines
系統視圖包含數據庫中所有存儲過程和函數以及有關它們的元數據的列表。 ( docs.microsoft.com )
如果得到結果,則可以運行以下查詢,即存在具有相同名稱的存儲過程。
select count(*)
from DatabaseName.information_schema.routines
where routine_type = 'PROCEDURE' and routine_name= 'YourProcedureName'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.