2016-12-16 80 views
0

我的目標是從vba函數執行sql server存儲過程,並檢查存儲過程是否返回任何記錄。VBA:如何捕獲存儲過程返回值

在VBA代碼我這個地步得到:

Function TestStoredProcedure() 

    Dim strMsg As String 

    Dim ADOCon As ADODB.Connection 
    Dim ADOQD As ADODB.Command 
    Dim ADORS As ADODB.Recordset 

    Set ADOCon = New ADODB.Connection 
    ADOCon.ConnectionString = GetConnectionString("Dev") 
    ADOCon.CommandTimeout = 0 
    ADOCon.Open 

    Set ADOQD = New ADODB.Command 
    ADOQD.ActiveConnection = ADOCon 
    ADOQD.CommandTimeout = 0 

    ADOQD.CommandType = adCmdStoredProc 
    ADOQD.CommandText = "mn_CheckForInvalidEntries" 

    'Execute 
    Set ADORS = ADOQD.Execute 

    If ADORS.RecordCount > 0 Then 

    strMsg = "The SLI Search Feed was not successful." 
      MsgBox strMsg, vbExclamation, "foo" 
    Else 
     strMsg = "The SLI Search Feed successful." 
      MsgBox strMsg, vbExclamation, "foo" 
    End If 

    ADOCon.Close 
    Set ADOQD = Nothing 
    Set ADOCon = Nothing 
    strMsg = "" 

End Function 

,並且存儲過程:

ALTER PROCEDURE [dbo].[mn_CheckForInvalidEntries] 
AS 
BEGIN 
    SET NOCOUNT ON; 
    SELECT 
     [ProductID] 
    , [ForSale] 
    FROM [Product] 
    WHERE [ProductID] IN 
     (
     SELECT 
      [SearchIndex].[ProductID] 
     FROM [dbo].[SearchIndex] 
     INNER JOIN [ProductData] 
      ON [dbo].[SearchIndex].[ProductID] = [ProductData].[ProductID] 
     WHERE [ForSale] = 1 
        AND [SearchIndex].[ProductID] NOT LIKE 'mn[d-g]%' 
        AND [Record] IS NULL 
        AND [SearchIndex].[ProductID] NOT LIKE 'mn[a-z]%' 
END; 

如果我能得到在得到檢查的部分如果SP返回的任何幫助價值觀,這將是偉大的。

謝謝。

+1

該程序看起來像它返回行,所以你嘗試分配一個ADO記錄集'Execute'的返回值? 'Set rs = ADOQD.Execute()'然後檢查'rs.EOF'並相應地執行。 –

+0

我有,而我得到的回報是-1。我正在更新我的vb代碼,以便您可以在等待某些評論,建議時看到我嘗試過的內容。 –

+3

不要使用'Recordcount'(它只對特定的遊標類型有效)來確定是否有任何記錄:如果沒有返回任何記錄,'ADORS.EOF'將爲True –

回答

3

要存儲結果,您可以使用記錄集。

Dim adoRs As ADODB.Recordset 
Set adoRs = ADOQD.Execute 

那麼你可以要求記錄是否爲空。

isEmpty = (adoRs.BOF And adoRs.EOF) 
0

所有你想要做的就是從Excel運行一個存儲過程,對吧?這裏有兩個選項可供您嘗試。

Option Explicit 

Sub Working2() 

Dim con As Connection 
Dim rst As Recordset 
Dim strConn As String 

Set con = New Connection 
strConn = "Provider=SQLOLEDB;" 
strConn = strConn & "Data Source=LAPTOP\SQL_EXPRESS;" 
strConn = strConn & "Initial Catalog=Northwind;" 
strConn = strConn & "Integrated Security=SSPI;" 

con.Open strConn 

'Put a country name in Cell E1 
Set rst = con.Execute("Exec dbo.TestNewProc '" & ActiveSheet.Range("E1").Text & "'") 

'The total count of records is returned to Cell A5 
ActiveSheet.Range("A5").CopyFromRecordset rst 

rst.Close 
con.Close 

End Sub 


Sub Working() 


Dim con As Connection 
Dim rst As Recordset 

Set con = New Connection 
con.Open "Provider=SQLOLEDB;Data Source=LAPTOP\SQL_EXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;" 

Set rst = con.Execute("Exec dbo.[Ten Most Expensive Products]") 
'Results of SProc are returned to Cell A1 
ActiveSheet.Range("A1").CopyFromRecordset rst 

rst.Close 
con.Close 
End Sub