我是VBA(宏)的新手,并且有一些要求从VBA运行存储过程。因此,我编写了我的第一个简单存储过程,但是在通过VBA代码执行时抛出错误,而在SQL Server中执行时它确实可以正常工作。我正在做一些我无法找到的愚蠢的错误。我很希望你们能一次性找到它。
存储过程:
-- ================================================
-- Template generated from Template Explorer using:
USE test
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
DROP PROCEDURE [dbo].[spEmployeeData]
GO
CREATE PROCEDURE [dbo].[spEmployeeData]
@empid INT = NULL -- parameter that can supply value as per requirement
AS
SELECT *
FROM employee
WHERE empid > ISNULL(@empid, empid)
Go
VBA代码:
Option Explicit
Private Sub Exec_StoredProc_Click()
Dim con As ADODB.Connection
Set con = New ADODB.Connection
Dim res As ADODB.Recordset
Dim mobjCmd As ADODB.Command
Set mobjCmd = New ADODB.Command
Dim strConn As String
'Dim strQuery As String
'con.Close
strConn = "Provider=SQLOLEDB; Data Source=localhost; Initial Catalog=test; Integrated Security=SSPI;"
con.Open strConn
With mobjCmd
.ActiveConnection = con
.CommandText = "Exec [dbo].[spEmployeeData]"
.CommandType = adCmdStoredProc
.CommandTimeout = 0
.Parameters.Append .CreateParameter("@empid", adInteger, adParamInput, 32767, 102)
' repeat as many times as you have parameters
.Execute
End With
'Debug.Print spEmployeeData
End Sub