Microsoft Knowledge Base Email Alertz

KBAlertz.com: (308624) - When you run an ADO.NET command, the output parameters may not be initialized, or they may return an incorrect value.

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: 308624 - Last Review: March 13, 2006 - Revision: 3.1

Output parameters are not returned when you run an ADO.NET command in Visual C++ .NET

This article was previously published under Q308624
Note Microsoft Visual C++ .NET (2002) supports both the managed code model that is provided by the Microsoft .NET Framework and the unmanaged native Microsoft Windows code model. The information in this article applies only to unmanaged Visual C++ code.
For a Microsoft Visual C# .NET version of this article, see 308621  (http://kbalertz.com/Feedback.aspx?kbNumber=308621/EN-US/ ) .
For a Microsoft Visual Basic .NET version of this article, see 308051  (http://kbalertz.com/Feedback.aspx?kbNumber=308051/EN-US/ ) .

This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System::Data::SqlClient

On This Page

SYMPTOMS

When you run an ADO.NET command, the output parameters may not be initialized, or they may return an incorrect value.

CAUSE

This behavior occurs if the direction of the parameter is not set properly. Output parameters are returned at the end of the data stream when you use a DataReader object.

RESOLUTION

To resolve this issue, do both of the following:
  • When you use a DataReader implementation, be sure to close it or read to the end of the data before the output parameters are visible.

    -and-
  • Make sure that the direction of the parameter is set to Output or InputOutput (if the parameter is used in the procedure to to both send and receive data).
Note Ensure that the parameter object for the return value is the first item in the Parameters collection. Additionally, ensure that the parameter's data type matches that of the expected return value.

STATUS

This behavior is by design.

MORE INFORMATION

Steps to reproduce the problem

  1. Create a stored procedure named "MyProc" in the Pubs database by running the following query in SQL Server Query Analyzer:
    CREATE proc MyProc
       @out smallint OUTPUT
       AS
       Select * from Titles
       Select @out = count(*) from titles
       GO
    						
    The stored procedure (MyProc) returns one output parameter ("@out").
  2. Start Microsoft Visual Studio .NET.
  3. Create a new Managed C++ project. Name the project "outParam."
  4. Copy and paste the following code in the outParam.cpp file, overwriting the existing code generated by Visual Studio .NET:
    #include "stdafx.h"
    
    #using <mscorlib.dll>
    #using <System.dll>
    #using <System.Data.dll>
    
    using namespace System;
    using namespace System::Data;
    using namespace System::Data::SqlClient;
    
    int direction(void);
    int reader (void);
    
    // This is the entry point for this application
    #ifdef _UNICODE
    int wmain(void)
    #else
    int main(void)
    #endif
    {
    	Console::WriteLine("Running the parameter direction method 'direction()' to check the return parameter value");
    	direction();
    	
    	Console::WriteLine("\nRunning the data reader method 'reader()' to check the return parameter value");
    	reader();
    
    	return 0;   
    }
    
    
    int direction(void)
    {
            String *myConnString = "Data Source=sql_server_name;User ID=your_user_id;password=your_password;Initial Catalog=pubs;";
            SqlConnection *myConnection = new SqlConnection(myConnString);
            SqlCommand *myCommand = new SqlCommand();
    
    		myCommand->CommandType = CommandType::StoredProcedure;
            myCommand->Connection = myConnection;
            myCommand->CommandText = "MyProc";
            myCommand->Parameters->Add("@out", SqlDbType::Int);
            
    
            SqlParameter *myParam = myCommand->Parameters->Item["@out"];
    	//Uncomment the following line to return proper output value
    	//myParam->Direction = ParameterDirection::Output;
            
    		try
    		{
                myConnection->Open();
                myCommand->ExecuteNonQuery();
    	    Console::Write("Return Value : {0} \n\n", myCommand->Parameters->Item["@out"]->Value->ToString());
    		}
            catch(Exception *ex) 
    		{
    			Console::Write(ex->ToString());
    		}
            __finally
    		{
                myConnection->Close();
    		}
    		
    		return 0;
    }
    
    int reader (void)
    {
            String *myConnString = "Data Source=sql_server_name;User ID=your_user_id;password=your_password;Initial Catalog=pubs;";
            SqlConnection *myConnection = new SqlConnection(myConnString);
            SqlCommand *myCommand = new SqlCommand();
            SqlDataReader *myReader;
    
    	myCommand->CommandType = CommandType::StoredProcedure;
            myCommand->Connection = myConnection;
            myCommand->CommandText = "MyProc";
    
    	myCommand->Parameters->Add("@out", SqlDbType::Int);
            SqlParameter *myParam = myCommand->Parameters->Item["@out"]; 
    	myParam->Direction = ParameterDirection::Output;
    
            try
    	{
                myConnection->Open();
                myReader = myCommand->ExecuteReader();
    
                //Uncomment the following line to return proper output value
                // myReader->Close();
    	    Console::Write("Return Value : {0} \n\n", myCommand->Parameters->Item["@out"]->Value->ToString());
    	}
            catch(Exception *ex)
    		{
    			Console::Write(ex->ToString());
    		}
            __finally
    		{
                myConnection->Close();
    		}
            return 0;
    
    }
  5. Modify the Connection string (myConnString), as appropriate for your environment.
  6. Save your project. On the Debug menu, click Start Without Debugging to run your project.
  7. Notice that the direction method appears to be uninitialized and to have thrown an exception:
    System.Data.SqlClient.SqlException: Procedure 'MyProc' expects parameter '@out', which was not supplied.
    Uncomment the line of code that sets the direction property for the output parameter, and then run the project again to produce the proper behavior.
  8. Now, notice that the reader method appears to be uninitialized and to have thrown an exception:
    System.NullReferenceException: Value null was found where an instance of an object was required.
    Uncomment the line of code that closes the reader object, and then re-run the project to produce the proper behavior.

REFERENCES

For more information, click the following article number to view the article in the Microsoft Knowledge Base:
308049  (http://kbalertz.com/Feedback.aspx?kbNumber=308049/ ) How to call a parameterized stored procedure by using ADO.NET and Visual Basic .NET

APPLIES TO
  • Microsoft ADO.NET (included with the .NET Framework)
  • Microsoft ADO.NET 2.0
  • Microsoft Visual C++ .NET 2002 Standard Edition
  • Microsoft Visual C++ .NET 2003 Standard Edition
Keywords: 
kbmanaged kbnofix kbprb kbsqlclient kbsystemdata KB308624
       

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

Be the first to leave feedback, to help others about this knowledge base article.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please