Introduction
This article explains how to use a Stored procedure in Visual Basic 6.0 using Microsoft ActiveX Data Objects(ADO). I tried to make it simple and I think this may be helpful for those who want to try stored procedures in VB6 applications. Here I will explain
-
The steps for writing a small stored procedure (in SQL Server 2000)
-
How to use that stored procedure in VB6.0
-
Using Output parameters in stored procedures
ActiveX Data Objects (ADO)
ActiveX Data Objects provide a set of objects, properties, and methods for applications that access and manipulate data. The commonly used ADO objects are Connection, Command, and Recordset.
Connection Object
Connection object establishes a connection to a data source. To create a Connection object, we need to supply the name of either an ODBC data source or an OLE DB provider.
ADO Connection Strings (CP article by Carlos Antollini)
Command object
A Command object is a definition of a specific command that we intend to execute against a data source.
CommandType property is used to specify the type of command used. Example includes adCmdText - Use if the query string is a SQL command. adCmdTable - Use if the query string is the name of a table name. adCmdStoredProc - Use if the query string is the name of a stored procedure.
Recordset object
Recordset represents the entire set of records from a database table or the results of an executed command.
Creating & Testing a simple Stored Procedure
A Stored Procedure is a set of one or more SQL statements that is precompiled and processed as a single task. The stored procedure exists in the database as an object, even after execution has finished. To know more about Stored procedures check out this CP article.
Everything you wanted to know about stored procedures (CP article by Himanshu Khatri)
Example:
In the SQL Enterprise Manager, expand the Northwind database, right click on the Stored Procedures and select New Stored Procedures, then write down the following example and click OK button.
CREATE PROCEDURE empdetails @empid int
AS
SELECT FirstName, Title, Address FROM Employees WHERE EmployeeID=@empid
GO
From the Tools option select SQL Query Analyser and test the stored procedure as below:
exec empdetails 1
Here exec is the command to execute a stored procedure empdetails is the procedure name and 1 is the employee id. Execute the procedure (F5), you can see the record displayed.
Using Stored Procedure in Visual Basic 6 (Example)
1) Create a new Project in Visual Basic.
2) On the form place the following controls in the order as shown in the figure:
- Three Labels (First Name, Title, Address)
- Four Textboxes (txt_empid, txt_firstname, txt_title, txt_address)
- One Command button (name= cmd_get, Caption=Get)

3) From the Project menu click References and select Microsoft ActiveX Data Objects 2.5 Library, and click OK.
4) On the General Declaration section (click on top of code window) enter the following code.
Option Explicit
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cmd As ADODB.Command
Dim str_empid, strconnect As String
Here Option Explicit force you to declare all variables that are used in the program (good programming practice), con is the connection object, rs is the recordset object cmd is the command object, which is used for specifying the command type and procedure name, str_empid is used to store employee id and strconnect for storing the connection string.
5) On the form load event (Form_Load) enter this:
Private Sub Form_Load()
strconnect = "Provider=SQLOLEDB;Data Source=suj;Initial Catalog=Northwind"
con.Open strconnect, "sa", ""
End Sub
Here SQLOLEDB is the database provider, suj is the system or computer name (will be different in your case) and Northwind is the database name, strconnect is the connection string, sa is username and password is null (this will be same as above unless you have changed it). con.Open opens the database connection.
6) On the Command button click event (cmd_get_Click) enter this:
Private Sub cmd_get_Click()
str_empid = txt_empid.Text
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "empdetails"
cmd.Parameters.Append cmd.CreateParameter("empid", adVarChar, adParamInput, 6, str_empid)
Set rs = cmd.Execute
If Not rs.EOF Then
txt_firstname = rs.Fields(0)
txt_title = rs.Fields(1)
txt_address = rs.Fields(2)
End If
Set cmd.ActiveConnection = Nothing
End Sub
Here we first assign the value of employee id in the Textbox (txt_empid) to str_empid. You should set cmd as a new command object and should specify the connection to be used(con), the command type (adCmdStoredProc � for Strored procedure), command text(empdetails � name of the stored procedure),the parameter and value (empid � parameter name, str_empid � employee id value). After that we execute the cmd and assign the value to rs (ADODB Recordset object). If the recordset (rs) contains some value, those values will be assigned to appropriate textboxes. Finally set the connection of cmd to none.
7) Execute the program (F5). Enter an employee id and click the Get button, you should get a similar result as below.

Using OUTPUT parameter in Stored Procedures
Output parameters allow the stored procedure to pass a value back to the caller program.
This will be useful for setting some status values that can be used in the programs.
Here is an example that uses an output parameter.
CREATE PROCEDURE update_empdetails @empid int,@firstname varchar(30),@title varchar(30) ,
@address varchar(100),@result int OUTPUT AS
Begin
update Employees set FirstName=@firstname,Title=@title,Address=@address WHERE EmployeeID=@empid;
set @result=1;
select @result;
EndGO
Here @result int OUTPUT is the output parameter, set @result=1 will set a value for the parameter select @result statement is needed only if you want to see the result in SQL Query Analyser.
To test the procedure in SQL Query Analyser :
update_empdetails 1, 'abc','Programmer','Address' , 0
Calling this procedure in VB:
1) Add one more Command button (name= cmd_update, Caption=Update) in your form as below.
2) In the button click event enter this code
Private Sub cmd_update_Click()
Dim res As Integer
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "update_empdetails"
cmd.Parameters.Append cmd.CreateParameter("empid", adVarChar, adParamInput, 6, txt_empid.Text)
cmd.Parameters.Append cmd.CreateParameter("firstname", adVarChar, adParamInput, 30, txt_firstname.Text)
cmd.Parameters.Append cmd.CreateParameter("title", adVarChar, adParamInput, 30, txt_title.Text)
cmd.Parameters.Append cmd.CreateParameter("address", adVarChar, adParamInput, 100, txt_address.Text)
cmd.Parameters.Append cmd.CreateParameter("result", adInteger, adParamOutput)
cmd.Execute
res = cmd("result")
If (res = 1) Then
MsgBox "Updated Successfully"
End If
Set cmd.ActiveConnection = Nothing
End Sub
Here cmd.Parameters.Append cmd.CreateParameter("result", adInteger, adParamOutput) is for specifying the output parameter.
result � name of the output parameter
adInteger �data type
adParamOutput �Parameter Direction Enum, for output parameter.
res = cmd("result")
This statement will assign the value of the result parameter to res.
3) Execute the program (F5). Enter an employee id and click the Get button, The values will be displayed in textboxes, then enter new values for First Name, Title and Address and click the Update button, the record is updated and you will get a message box saying "Updated Successfully".
ADO Reference:
Distributed Applications for Microsoft Visual Basic 6.0 MCSD Training Kit.
| You must Sign In to use this message board. |
|
|
 |
|
 |
Hello !
I've just find out your code and I think it is fantastic ! But i don't understand the use of CreateParameter before Execute. What is the utility of the string first parameter in cmd_get_Click works? In fact, how to know the parameter number ?
And after, I try to use your code with ORACLE DBMS !! I have added "cmd.Parameters.Refresh" before the use of CreateParameter and strangely, the program crashes when the provider is oracle built one and it is OK when the provider is microsoft one. WHY ?
To promote computer science in Africa !
modified on Friday, April 18, 2008 7:03 AM
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
 |
Hello!
I am trying to apply this on my Access VBA. However, I get an error saying
Runtime Error 3704: Operation is not allowed when the object is closed
on the following code, and it highlighted the 'If Not rs.EOF Then' ... set rs = cmd.Execute
If Not rs.EOF Then Debug.Print rs.RecordCount Else Debug.Print "Empty" End If
Why is this so?
Vinz
|
| Sign In·View Thread·PermaLink | 2.00/5 |
|
|
|
 |
|
|
 |
|
 |
Hi there, in your explanation you mentioned....
"You should set cmd as a new command object"
Set cmd = new adodb.command
....why is that necessary? since we use
Dim cmd as adodb.command
I understand that we DIDN'T use the NEW keyword in
Dim cmd as adodb.command, but I would like to know why we DIDN'T use the NEW keyword in declaring the command object and why we DID use the NEW keyword for the connection object and the recordset object.
I would appreciate it if you could explain this.
Also could you explain what exactly happens when we write
Dim cmd as adodb.command
and what happens when we write
Set cmd = new adodb.command
what's the difference between them.
Thanx
Kinara 
-- modified at 12:56 Wednesday 4th April, 2007
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
 |
Hi Kinara,
Your question is a nice one and I am happy that you read the article throughly otherwise you won't ask this question.
Kinara wrote: could you explain what exactly happens when we write
Dim cmd as adodb.command
and what happens when we write
Set cmd = new adodb.command
what's the difference between them.
what is the differece between a dim statement and a dim statement with a "New" keyword ?
Dim statement is used to declare one or more variables or objects. If the New keyword is used, then an implicit creation of the object is made.
Dim cmd As ADODB.Command ' This will declare the object variable.
Set cmd = New ADODB.Command ' Instantiate the object variable
Also you can find that
Dim i as Interger 'This will declare the variable as Interger type.
Dim i as New Integer ' Error - You Can't do this since Integer is not an object type
Kinara wrote: I would like to know why we DIDN'T use the NEW keyword in declaring the command object and why we DID use the NEW keyword for the connection object and the recordset object.
Dim con As New ADODB.Connection 'This will declare and instantiate the object variable
We are using a single connection object through out the project and hence it is declared in the global declaration section (Same with recordset).
As you know when an object is created , its values persist. In the case of cmd (command object) "cmd.Parameters.Append" changes in two cases.
by using
Set cmd = New ADODB.Command
we ensure that each time a new command object is created, upon which we do our operations.
Thanks & Regards
Sujith
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
 |
hi here is a copy of a cde i use topen my data base but i get this error saying sql not available or i do not have access or permission and i am using a windows authentication. pls is anything wrong and please i need help am running man.
<<i>big>Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim con As ADODB.Connection con = New ADODB.Connection con.ConnectionString = "Provider=SQLOLEDB;UID=;pwd=;" & "Data Source=employee;Initial Catalog=pencom_standalone" con.Open()
stivisa
|
| Sign In·View Thread·PermaLink | 2.00/5 |
|
|
|
 |
|
 |
hi stivisa,
Data Source=employee, here "employee" should be the computer name you are using, if not use your computer name.
if you created a dsn, then you can open the connection by
con.open "employee","",""
ie dsn name, userid, pass . it is better to give a uid and password.
Sujith
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
 |
How do you get the return value from SP if not specifically declared within the SP? Example: CREATE procedure sp_ValidateStudent ( @StudentID as nvarchar(40), @Password as nvarchar(8) ) as if (select count(StudentID) from Students where StudentID = @StudentID and Password = @Password) > 0 begin return 1 end else begin return 0 end GO
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
 |
I know it's been a while since this question was asked, but here's the answer. Maybe it will help someone else searching for this. You have to manually create an extra parameter in your VB code. It should look like this:
cmd.Parameters.Append cmd.CreateParameter("ReturnVal", adInteger, adParamReturnValue)
From what I've read, the restrictions on it are as follows: It must be the first parameter you create/append. It must be of type "adInteger". However, from what I can tell, it doesn't matter what you name it. After you execute the command, you may check it's value as you would an output parameter; i.e. ReturnValue = cmd.Parameters("ReturnVal")
|
| Sign In·View Thread·PermaLink | 5.00/5 |
|
|
|
 |
|
 |
In fact, if the stored procedure is like that, how to do ?
CREATE PROCEDURE empdetails @empid int, @response nvarchar AS SELECT @response = FirstName FROM Employees WHERE EmployeeID=@empid GO
How to retrieve the response value after the execution of the stored proc?
And can we get the result without using
cmd.Parameters.Append cmd.CreateParameter("empid", adVarChar, adParamInput, 6, str_empid) For example, to use cmd.Parameters.Refresh and to know the parameters' count and to get them by parameter number ?
To promote computer science in Africa !
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
 |
The example was very useful for me, you have taken care to make it simple. Now i have a simple question. I have my own database and a dsn for the same. How can i connect using the dsn.
|
| Sign In·View Thread·PermaLink | 2.00/5 |
|
|
|
 |
|
 |
As I have mentioned in the article, to create a Connection object, you need to supply the name of either an ODBC data source or an OLE DB provider. In the example I used the SQLOLEDB provider.
Private Sub Form_Load() strconnect = "Provider=SQLOLEDB;Data Source=suj;Initial Catalog=Northwind" con.Open strconnect, "sa", "" End Sub
If you have created a dsn, it is easy to connect to the database. You only need to specify the dsn name , username and password in the open method of the Connection object. Say if your dsn name is "abc" , username is "user" and passsword is "pass". Then use the following statement.
Private Sub Form_Load() con.Open "abc","user","pass" End Sub
Sujith
|
| Sign In·View Thread·PermaLink | 2.00/5 |
|
|
|
 |
 | Missing  Devlin Schoonraad | 0:58 7 Sep '06 |
|
 |
The source code (simple_sp_vb6.zip) for this article appears to be missing :->
There's no place like 127.0.0.1
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
 |
However, at least in older versions of ADO, order is important in stored procedure calls against SQL Server. Usually requiring the ampersand. Also, this article would be an excellent place to throw in the use of prepared commands. Also with your example I think a fast forward read only cursor should be specified, although ADO may ignore it.
On two occasions I have been asked [by members of Parliament], 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. - Charles Babbage
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
 |
Please see the "Using OUTPUT parameter in Stored Procedures" section of the article. I think this is what you asked.Thanks for your question.
sujithcjose@yahoo.com http://www.sujith.cjb.net
|
| Sign In·View Thread·PermaLink | 1.50/5 |
|
|
|
 |
|
|