Executing Stored Procedures
A stored procedure is a precompiled executable object that contains one or more SQL statements. Stored procedures can have input and output parameters and can issue an integer return code.
Executing a stored procedure is similar to executing a prepared statement, except that the stored procedure exists as a permanently compiled object in the database. A stored procedure can also be used to hide complex SQL statements from the application.
When executing a stored procedure in a Command object, the CommandType property must be specified with the adCmdStoredProc value. With adCmdStoredProc, the corresponding SQL statement for the underlining provider is generated. For applications that use the Microsoft OLE DB Provider for ODBC (MSDASQL), ODBC escape sequences for procedure calls are generated.
There is no need to prepare a statement that calls only a stored procedure. Both stored procedures and prepared statements are methods of precompiling statements. Because a stored procedure is precompiled, preparing a stored procedure call adds overhead. The prepared statement adds a small precompiled execution plan that calls the stored procedure execution plan, rather than executing the stored procedure execution plan directly.
This example shows the execution of the sp_who SQL Server system stored procedure:
Dim cn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
cn.Provider = "sqloledb"
cn.Properties("Data Source").Value = "MyServerName"
cn.Properties("Initial Catalog").Value = "northwind"
cn.Properties("Integrated Security").Value = "SSPI"
cn.Open
Cmd.ActiveConnection = cn
Cmd.CommandText = "sp_who"
Cmd.CommandType = adCmdStoredProc
Set rs = Cmd.Execute
Debug.Print rs(0)
rs.Close