Microsoft Knowledge Base Email Alertz

KBAlertz.com: (309486) - This step-by-step describes how to call a parameterized SQL Server stored procedure using the ODBC .NET Managed Provider and Visual Basic .NET. Although executing a parameterized stored procedure using the ODBC .NET Provider is slightly different from...

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
The ad says 3 - but KBAlertz referrals get
** SIX MONTHS FREE **


Bug Tracking Software
For bug tracking software or defect tracking software or issue tracking software, visit Axosoft.


Community Site



We Send hundreds of thousands of emails using ASP.NET Email



Expert Web Design & Graphic Design
Design44.com

ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
The ad says 3 - but KBAlertz referrals get
** SIX MONTHS FREE **




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




Article ID: 309486 - Last Review: March 29, 2007 - Revision: 4.2

How To Execute SQL Parameterized Stored Procedures by Using the ODBC .NET Provider and Visual Basic .NET

This article was previously published under Q309486

On This Page

SUMMARY

This step-by-step describes how to call a parameterized SQL Server stored procedure using the ODBC .NET Managed Provider and Visual Basic .NET.

Although executing a parameterized stored procedure using the ODBC .NET Provider is slightly different from executing the same procedure using the SQL or the OLE DB Provider, there is one important difference -- the stored procedure must be called using the ODBC CALL syntax rather than the name of the stored procedure. For additional information on this CALL syntax, see the page entitled "Procedure Calls" in the ODBC Programmer's Reference in the MSDN Library.

Call Syntax Examples

  1. Here is an example of the call syntax for an actual stored procedure in the Northwind sample database that expects one input parameter:
    {CALL CustOrderHist (?)}
    					
  2. Here is an example of the call syntax for a stored procedure that expects one input parameter and returns one output parameter and a return value. The first placeholder represents the return value:
    {? = CALL Procedure1 (?, ?)
    					
  3. The ODBC .NET Managed Provider, like the OLE DB Provider, processes parameters by ordinal position (zero-based) and not by name.
  1. If you have not already done so, download and install the ODBC .NET Managed Provider from the following Microsoft Web site:
    http://www.microsoft.com/downloads/details.aspx?familyid=6ccd8427-1017-4f33-a062-d165078e32b1&displaylang=en (http://www.microsoft.com/downloads/details.aspx?familyid=6ccd8427-1017-4f33-a062-d165078e32b1&displaylang=en)
  2. Start Visual Studio .NET, and then create a new Visual Basic .NET Windows Application.
  3. On the Project menu, click Add Reference. On the .Net tab, double-click Microsoft.Data.ODBC.dll to add a reference to the Microsoft.Data.ODBC namespace.
  4. At the very top of the code window, add the following statement:
    Imports Microsoft.Data.ODBC
    					
  5. Add a command button to the default form from the Toolbox.
  6. Double-click the command button to switch to the code window for the button Click event. Paste the following code in the Click event procedure, adjusting the SQL Server connection string as necessary:
            Dim cn As OdbcConnection
    
            Try
                cn = New OdbcConnection("Driver={SQL Server};Server=(local);Database=Northwind;Trusted_Connection=Yes")
    
                Dim cmd As OdbcCommand = New OdbcCommand("{call CustOrderHist (?)}", cn)
    
                Dim prm As OdbcParameter = cmd.Parameters.Add("@CustomerID", OdbcType.Char, 5)
                prm.Value = "ALFKI"
    
                cn.Open()
    
                Dim dr As OdbcDataReader = cmd.ExecuteReader()
    
                While dr.Read
                    Console.WriteLine(dr.GetString(0))
                End While
                dr.Close()
    
            Catch o As OdbcException
    
                MsgBox(o.Message.ToString)
    
            Finally
    
                cn.Close()
    
            End Try
    					
  7. Run the project. This code calls the "CustOrderHist" stored procedure, passing in the CustomerID as a single input parameter, and returns a resultset. In the Output window, you should see the list of products ordered by Northwind customer ALFKI.
  1. Using Query Analyzer, create the following stored procedure in the Northwind sample database. This stored procedure accepts a CustomerID as an input parameter and returns a list of orders placed by the customer, returns the average freight per order paid by that customer as an output parameter, and returns the number of orders placed by the customer as a return value.
    CREATE PROCEDURE usp_TestParameters
    @CustID CHAR(5),
    @AvgFreight MONEY OUTPUT
    AS
    SELECT @AvgFreight = AVG(Freight) FROM Orders WHERE CustomerID = @CustID
    SELECT * FROM Orders WHERE CustomerID = @CustID
    RETURN @@ROWCOUNT
    					
  2. Repeat steps 1 through 6 above, substituting the following code in the Click event procedure of the command button:
            Dim cn As OdbcConnection
    
            Try
                cn = New OdbcConnection("Driver={SQL Server};Server=(local);Database=Northwind;Trusted_Connection=Yes")
    
                Dim cmd As OdbcCommand = New OdbcCommand("{? = call usp_TestParameters (?, ?)}", cn)
    
                Dim prm As OdbcParameter = cmd.Parameters.Add("@RETURN_VALUE", OdbcType.Int)
                prm.Direction = ParameterDirection.ReturnValue
    
                prm = cmd.Parameters.Add("@CustomerID", OdbcType.Char, 5)
                prm.Value = "ALFKI"
    
                prm = cmd.Parameters.Add("@AvgFreight", OdbcType.Double)
                prm.Direction = ParameterDirection.Output
    
                cn.Open()
    
                Dim dr As OdbcDataReader = cmd.ExecuteReader()
    
                While dr.Read
                    Console.WriteLine(dr.GetString(0))
                End While
                dr.Close()
    
                Console.WriteLine("Average Freight (output param): {0}", cmd.Parameters(2).Value)
                Console.WriteLine("Order Count (return value): {0}", cmd.Parameters(0).Value)
    
    
            Catch o As OdbcException
    
                MsgBox(o.Message.ToString)
    
            Finally
    
                cn.Close()
    
            End Try
    					
  3. Run the project. This code calls the "usp_TestParameters" stored procedure that we created in step 1 above, passing in the CustomerID as a single input parameter, and returns a resultset, an output parameter and a return value. In the Output window, you should see the list of orders placed by Northwind customer ALFKI, the average freight the customer paid per order, and the count of orders.

  1. The ADO syntax that is usually used to call stored procedures, where the name of the procedure alone is provided as the CommandText, cannot be used with the ODBC .NET Managed Provider.
  2. When a stored procedure returns a resultset, the output parameter(s) and return value are not available until the resultset has been accessed and closed. For example, if we omitted the line "dr.Close()" in the second sample above, we would be unable to retrieve the values for the output parameter and the return value.
  3. The ODBC .NET Managed Provider, like the OLE DB Provider, processes parameters by ordinal position (zero-based) and not by name.
  4. The ODBC .NET Managed Provider does not ship with Visual Studio .NET, but must be downloaded separately.

REFERENCES

For additional information on the ODBC CALL syntax, see the topic "Procedure Calls" in the ODBC Programmer's Reference in the MSDN Library.


APPLIES TO
  • Microsoft ADO.NET (included with the .NET Framework)
  • Microsoft ADO.NET 1.1
  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft Visual Basic .NET 2003 Standard Edition
Keywords: 
kbhowtomaster kbsystemdata kbdatabase KB309486
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Brian Report As Irrelevant  
Written: 12/3/2004 5:08 PM
Thank You! Being new to both VB.Net and SQL Server 2000, I really needed to know how to call stored procedures with parameters. This helped get me over the hump! Thanks again!

Mark Report As Irrelevant  
Written: 12/6/2005 10:08 AM
Very useful - you should ask MS for a job! Thanks

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please