Examples of using System.Data.ParameterDirection with Sql Server

When working with the SqlCommand you will no doubt have to supply parameters to your command whether it be a Stored Procedure or Text command.  Although not as efficient as an actual Stored Procedure there are some powerful things you can achieve using the System.Data.ParameterDirection, or rather other than just Input.

The enumeration holds the following values:

  • Input
  • InputOutput
  • Output
  • ReturnValue

In this article I will give a working example of each, simple but you will see the idea.  At the end I will make a custom object which I will populate using some of these directions.

For this example I am working with the AdventureWorks Database for Sql Server 2005.

Input

The most common direction.

            using (System.Data.SqlClient.SqlConnection sc1 = 
                new System.Data.SqlClient.SqlConnection(@"Data Source=REA_ANDREW-PC\SQLEXPRESS;Initial Catalog=AdventureWorks;"+
                    "Integrated Security=True"))
            {
                sc1.Open();
                using (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())
                {
                    command1.CommandType = CommandType.Text;
                    command1.Connection = sc1;
                    // DIRECTION :: Input
                    command1.CommandText = "INSERT INTO [Purchasing].[ShipMethod] (Name,ShipBase,ShipRate)"+
                        "VALUES (@Name,@ShipBase,@ShipRate)";
                    //Method 1
                    command1.Parameters.AddWithValue("@Name", "MyShippingMethod");
                    //Method 2
                    System.Data.SqlClient.SqlParameter parameter2 = 
                        new System.Data.SqlClient.SqlParameter("@ShipBase", 10.00M);
                    parameter2.Direction = ParameterDirection.Input;
                    command1.Parameters.Add(parameter2);
                    //Method 3 //Deprecated for AddWithValue
                    command1.Parameters.Add("@ShipRate", 10.00M);

                    command1.ExecuteNonQuery();
                }
            }

 

Here I have displayed three different syntactical ways of adding parameters to your SqlCommand.  The third and final way is deprectaed and you will see this if you try inside Visual Studio.  Because of this it will not appear inside intellisense.

 

InputOutput

For this example I will supply the parameter with a value and during the command I will modify its value and return the new value inside the parameter.  For the purposes of this example I will give it an initial value of 1 and when it has completed its execution its value should be 1 + the number of records inside the [Purchasing].[ShipMethod] table i.e. 7.

 

            using (System.Data.SqlClient.SqlConnection sc1 = 
                new System.Data.SqlClient.SqlConnection(@"Data Source=REA_ANDREW-PC\SQLEXPRESS;Initial Catalog=AdventureWorks;"+
                    "Integrated Security=True"))
            {
                sc1.Open();
                using (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())
                {
                    command1.CommandType = CommandType.Text;
                    command1.Connection = sc1;
                    // DIRECTION :: Input
                    command1.CommandText = "select @MyParameter = @MyParameter + Count(*) FROM [Purchasing].[ShipMethod]";
                    System.Data.SqlClient.SqlParameter paramter1 = command1.Parameters.Add("@MyParameter", SqlDbType.SmallInt);
                    paramter1.Value = 1;
                    paramter1.Direction = ParameterDirection.InputOutput;
                    command1.ExecuteNonQuery();
                    //The following value is now 7 after intially being 1
                    int newValue = (int)paramter1.Value;
                }
            }

Output

The output is going to look like the above example only I will not give it an intial value and simply assign the value inside the command text.

            using (System.Data.SqlClient.SqlConnection sc1 = 
                new System.Data.SqlClient.SqlConnection(@"Data Source=REA_ANDREW-PC\SQLEXPRESS;Initial Catalog=AdventureWorks;"+
                    "Integrated Security=True"))
            {
                sc1.Open();
                using (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())
                {
                    command1.CommandType = CommandType.Text;
                    command1.Connection = sc1;
                    // DIRECTION :: Input
                    command1.CommandText = "select @MyParameter = Count(*) FROM [Purchasing].[ShipMethod]";
                    System.Data.SqlClient.SqlParameter paramter1 = command1.Parameters.Add("@MyParameter", SqlDbType.SmallInt);
                    paramter1.Direction = ParameterDirection.Output;
                    command1.ExecuteNonQuery();
                    //The following value is now 6, the number of records inside the table
                    int newValue = (int)paramter1.Value;
                }
            }

Return Value

The return value is something which you will return at the end of the statement/s.  For this example I need to create a short stored procedure, again i will simply return the count of records from the table:

ALTER PROCEDURE CountRows

AS
Declare @CountR int
SELECT @CountR = Count(*) FROM [Purchasing].[ShipMethod]

RETURN @CountR

And so the function which will now work with this, and using the ReturnValue direction is as follows:

            using (System.Data.SqlClient.SqlConnection sc1 = 
                new System.Data.SqlClient.SqlConnection(@"Data Source=REA_ANDREW-PC\SQLEXPRESS;Initial Catalog=AdventureWorks;"+
                    "Integrated Security=True"))
            {
                sc1.Open();
                using (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())
                {
                    command1.CommandType = CommandType.StoredProcedure;
                    command1.Connection = sc1;
                    // DIRECTION :: Input
                    command1.CommandText = "CountRows";
                    System.Data.SqlClient.SqlParameter paramter1 = command1.Parameters.Add("@CountR", SqlDbType.SmallInt);
                    paramter1.Direction = ParameterDirection.ReturnValue;
                    command1.ExecuteNonQuery();
                    //The following value is now 6, the number of records inside the table
                    int newValue = (int)paramter1.Value;
                }
            }

 

The simple example object

I now want to use these counting methods to construct a sample object which will contain simply.

  1. Total Record Count
  2. List<string> of Shipping Names which can be bound to

This is just for an example, I realise lol that I could simply use the List<string> Count property BUT think of it like this.  What if you wanted to create a paged object so the list actual only contains say ten items because of a page size you set BUT you still have knowledge of the total number of records through the Total Record Count property, from which you could calculate the total number of pages.!! :-)

 

The object

namespace WindowsForm_Examples_NET_2
{
    class SimpleObjectOne
    {
        private int _recordCount;
        private List<string> _shippingNames;

        public List<string> ShippingNames
        {
            get { return _shippingNames; }
            set { _shippingNames = value; }
        }

        public int RecordCount
        {
            get { return _recordCount; }
            set { _recordCount = value; }
        }
        public SimpleObjectOne()
        {
            _shippingNames = new List<string>();
        }
        [System.ComponentModel.DataObjectMethod(
            System.ComponentModel.DataObjectMethodType.Select)]
        public static SimpleObjectOne GetSimpleObjectOne()
        {
            SimpleObjectOne objectOne = new SimpleObjectOne();
            objectOne.Execute();
            return objectOne;
        }

        private void Execute()
        {
            using (System.Data.SqlClient.SqlConnection sc1 =
    new System.Data.SqlClient.SqlConnection(@"Data Source=REA_ANDREW-PC\SQLEXPRESS;Initial Catalog=AdventureWorks;" +
        "Integrated Security=True"))
            {
                sc1.Open();
                using (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())
                {
                    command1.CommandType = System.Data.CommandType.Text;
                    command1.Connection = sc1;
                    // DIRECTION :: Input
                    command1.CommandText = "SET @CountRows = (SELECT Count(*) as COUNTR FROM [Purchasing].[ShipMethod]);" +
                        "SELECT Name FROM [Purchasing].[ShipMethod];";
                    System.Data.SqlClient.SqlParameter parameter1 =
                        command1.Parameters.Add("@CountRows", System.Data.SqlDbType.Int);
                    parameter1.Direction = System.Data.ParameterDirection.Output;
                    using (System.Data.SqlClient.SqlDataReader reader = command1.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            _shippingNames.Add(reader["Name"] as string);
                        }
                    }
                    RecordCount = (int)parameter1.Value;
                    //The following value is now 6, the number of records inside the table
                }
            }
        }
    }
}

An important note to make here, is if you are using the ExecuteReader on a statement and pass in Output parameters, you must close the data reader before you can access these output parameter values.  In the above you will see that I encase the data reader in a using statement block.

And finally to consume this example I use the following three lines:

            SimpleObjectOne newObject = SimpleObjectOne.GetSimpleObjectOne();
            int RecordCount = newObject.RecordCount;
            List<string> names = newObject.ShippingNames;

 

I now have 6 as the record count and a list of shipping names.

 

Cheers Andrew

Published Tuesday, February 19, 2008 10:22 AM by REA_ANDREW

Comments

# re: Examples of using System.Data.ParameterDirection with Sql Server

Friday, February 22, 2008 9:50 AM by Eric Newton

Andrew, you should warn that return values are short ints (-32K to 32K) range...

I see a lot of even expert SQL programmers get tripped up by this, by returning an IDENTITY column that finally hit the 32K mark.

(Haven't tested this in SQL 2008)

# re: Examples of using System.Data.ParameterDirection with Sql Server

Friday, February 22, 2008 12:04 PM by REA_ANDREW

Eric thanks for the comment but I do not agree.  The return value is what ever type I make it, so I made it an Int.  I then tested this by assigning the value of 1 billion to it

ALTER PROCEDURE [dbo].[CountRows]

AS

Declare @CountR int

SELECT @CountR = Count(*) FROM [Purchasing].[ShipMethod]

SET @CountR = 1000000000

RETURN @CountR

the using the code in my example above, with return values, I set a break point where it gets the return value and it retrieves no problem.  

I am using Visual Studio 2005 not 2000, I have not tested in 2000 so I am not sure if you are referring to that.  I cannot see it my self otherwise it would negate the need for choosing type if you can only return short int.  Where did you get your information from?

Cheers

Andrew

# re: Examples of using System.Data.ParameterDirection with Sql Server

Friday, February 22, 2008 12:09 PM by REA_ANDREW

I meant to say I am using Sql Server 2005 not 2000 lol :-)

# re: Examples of using System.Data.ParameterDirection with Sql Server

Wednesday, April 01, 2009 3:03 PM by Axel

I think Eric is pointing that 1000000000 of 10 digits may be returned fine to an int variable, but a number like 9999999999 (still 10 digits) will throw an exception.

Cheers

# re: Examples of using System.Data.ParameterDirection with Sql Server

Monday, July 13, 2009 10:02 AM by Natalia

Thanks. Very good examples.

# re: Examples of using System.Data.ParameterDirection with Sql Server

Friday, March 26, 2010 7:46 AM by Anlon

Hi guys. Hollywood is a place where they place you under contract instead of under observation. Help me! Looking for sites on: Turbo tax delux. I found only this - <a href="turbo-tax.biz/.../">tax cut turbo</a>. Cut intense and incorporate lighting sunrises, form still the most super-conscious or large games, adjust to scientists that will regulate your life of awareness, turbo tax. Turbo tax, in the same sensations, it may have been centered to as a question cheating, but hinterland has been deleted by e-mail, children and brings, only with service on models. Best regards :-(, Anlon from Madagascar.

# re: Examples of using System.Data.ParameterDirection with Sql Server

Thursday, August 05, 2010 9:12 PM by vinix

Some text have black background and foreground, and the code examples are clipped.

Please fix your css.

# re: Examples of using System.Data.ParameterDirection with Sql Server

Wednesday, September 08, 2010 7:50 AM by suthaRaghavan

still it has to be explain(little elabrate). pl i'm new to this field.

# re: Examples of using System.Data.ParameterDirection with Sql Server

Sunday, February 12, 2012 4:45 AM by IURiWdxnqnfhaJh

57m3lX It's straight to the point! You could not tell in other words! :D

Leave a Comment

(required) 
(required) 
(optional)
(required)