我正在尝试在2008 sql server上运行存储过程。我创建了单行proc,dbo.sp_test_proc。 我可以在服务器上通过EXEC运行proc,然后返回。 但是,当我尝试在excel / vba中通过ADO运行时,我收到错误消息'无法找到存储过程sp_test_proc。 我可以通过ADO运行sys schema存储过程,但不能运行任何dbo。我在角色db_owner中,并且vba代码在服务器管理工作室中创建存储过程的相同Windows用户下运行。 有人有任何想法吗?我很难过。
Sub storedProcedure()
'This sub-routine defines an ADOBD command to return variables to VBA from SQL Stored Procedures.
'The ADODB command executes a Stored Procedure on the SQL Server (cmd.CommandText = [Stored Procedure Name])
'Input requirements from the Stored procedure are declared as variants at the start of the sub-routine.
Dim cnt As ADODB.connection
Dim rst As ADODB.recordset
Dim cmd As ADODB.Command
Dim stCon As String 'SQL Connection string
Dim stProcName As String 'Stored Procedure name
'Declare variables for Stored Procedure
Dim myVariable As Variant
Dim myReturn As String
'Set ADODB requirements
Set cnt = New ADODB.connection
Set rst = New ADODB.recordset
Set cmd = New ADODB.Command
'Define database connection string
stCon = "Provider=SQLOLEDB.1;"
stCon = stCon + "Data Source=myserver;"
stCon = stCon + "Initial Catalogue=Mmydb;"
stCon = stCon + "Integrated Security=SSPI;"
stCon = stCon + "Persist Security Info=True;"
'Open database connection
cnt.ConnectionString = stCon
cnt.Open
' Defines the stored procedure commands
stProcName = "dbo.my_sp" 'Define name of Stored Procedure to execute."
'stProcName = "sys.sp_stored_procedures" 'Define name of Stored Procedure to execute.
cmd.CommandType = adCmdStoredProc 'Define the ADODB command
cmd.ActiveConnection = cnt 'Set the command connection string
cmd.CommandText = stProcName 'Define Stored Procedure to run
'Execute stored procedure and return to a recordset
Set rst = cmd.Execute()
'myReturn = rst.Fields("procedure_name").Value
myReturn = rst.Fields("mycolumn").Value
'Call Sub-Routine_That_Uses_The_Returned_Data
MsgBox (myReturn)
'Close database connection and clean up
If CBool(rst.State And adStateOpen) = True Then rst.Close
Set rst = Nothing
If CBool(cnt.State And adStateOpen) = True Then cnt.Close
Set cnt = Nothing
End Sub
答案 0 :(得分:0)
我真的要感谢大家,因为这篇帖子帮助我修复了'3小时问题'为什么hel * vba ADODB代码不起作用!
我只想补充说,在我的情况下,它无法正常工作设置rst = cmd.Execute() 我需要将其更改为:设置rst = cmd.Execute(,, adCmdStoredProc)
另外,我错了: InitialCatalog = 。正确的是:初始目录= 在这种情况下,错误消息实际上是无益的,因为它说:“找不到存储过程...”