What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 21075 |  Welcome, Guest!   Register  Login
Home > Articles > ADO.NET > How to retrieve @@identity auto incremented value using OUTPUT paramter through stored procedure and C#

How to retrieve @@identity auto incremented value using OUTPUT paramter through stored procedure and C#

2 vote(s)
Rating: 5 out of 5
Article posted by Dhirendra on 8/24/2011 | Views: 5959 | Category: ADO.NET | Level: Intermediate | Points: 250 red flag


In this article, we will earn how to get the value from output parameter in C# which is returned by stored procedure; also we will see how to get the newly inserted record’s Incremented PK value using output parameter. In this article we used @@Identity sql server variable which tracks the incremented value on the table.

Introduction


In this article, we will learn how to get the value from output parameter in C#  which is returned by stored procedure; also we will see how to get the newly inserted record’s Incremented PK value using output parameter. In this article we used @@Identity sql server variable which tracks the incremented value on the table.

 

The following example uses dbo.InsertEmployee stored procedure by passing require input parameters and a output paramter. This output parameter will returned the increamented PK to the caller.

 

This is one of the very good technique to insert the record in a table and retrieve the newly inserted record Pk Value using output parameter.

 

Following is the Employee table schema. Please note that Emp_Pk column is auto incremented so we don’t need to insert the value explicitly in that column.

 

 

 

Follwing is the stoerd procedure code.

 

Create PROCEDURE dbo.InsertEmployee

@FName varchar(50)

,@LName varchar(50)

,@Address varchar(50)

,@Emp_Pk INT output

AS

BEGIN

            INSERT INTO [dbo].[Employee]

                     ([FName]

                     ,[LName]

                     ,[Address])

             VALUES

                     (@FName

                     ,@LName

                     ,@Address)

      select @Emp_Pk =@@identity

END

Following is a employee class which has similar properties defined which we can used to insert the records.

 

public class Employee

    {

        public int EmpId { get; set; }

        public string Address { get; set; }

        public string FName { get; set; }

        public string LName { get; set; }

 

    }

 

Following is the code where we create the connection object and command object. Also we add the input paramters to the command object and finally we add the output paramter into the command object.

 

        private static void InsertEmployee()

        {

            Employee empObj = new Employee() { FName = "Dhirendra", LName = "Patil", Address = "Pune, India" };

            IDbConnection conn = new SqlConnection("ConnectionString");

            IDbCommand cmd = conn.CreateCommand();

            cmd.CommandType = CommandType.StoredProcedure;

            cmd.CommandText = "dbo.InsertEmployee";

            IDbDataParameter param = cmd.CreateParameter();

            param.Direction = ParameterDirection.Input;

            param.ParameterName = "@FName";

            param.DbType = DbType.String;

            param.Value = empObj.FName;

            cmd.Parameters.Add(param);

 

            param = cmd.CreateParameter();

            param.Direction = ParameterDirection.Input;

            param.ParameterName = "@LName";

            param.DbType = DbType.String;

            param.Value = empObj.LName;

            cmd.Parameters.Add(param);

 

            param = cmd.CreateParameter();

            param.Direction = ParameterDirection.Input;

            param.ParameterName = "@Address";

            param.DbType = DbType.String;

            param.Value = empObj.EmpId;

            cmd.Parameters.Add(param);

 

            param = cmd.CreateParameter();

            param.Direction = ParameterDirection.Output;

            param.ParameterName = "@Emp_Pk";

            param.DbType = DbType.Int32;

            cmd.Parameters.Add(param);

            conn.Open();

            int i = cmd.ExecuteNonQuery();

            conn.Close();

            param = (IDbDataParameter)cmd.Parameters["@Emp_Pk"];

            Console.WriteLine(param.Value.ToString());

        }

 

If you see the above code you will realized that we can only access the output paramater & its value after closing the connection object.

 

Conclusion


Hope this article helps!  Thanks for reading and let me know your feedback, comments.


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:8 year(s)
Home page:http://www.dotnetfunda.com
Member since:Tuesday, March 23, 2010
Level:Starter
Status: [Member]
Biography:
 Responses
Posted by: Samarmir | Posted on: 22 Jun 2012 11:06:40 AM | Points: 25

Thanks a lot for this.
I have been struggling with this.
I was not aware of this (you will realized that we can only access the output paramater & its value after closing the connection object), cleared out everything.

Again thanks.

>> Write Response - Respond to this post and get points
Related Posts

Im going to expail the various difference between GridView and the DataGrid controls and their different logics.

DataTableReader is a very useful ADO.NET class that can be used to retrieve / pass the data between layers in readonly and forward only format. In this article, I shall discuss about the DataTableReader class. Its very useful but perhaps rarely used in everyday programming even if it is best suitable in passing data between layers in place of DataTable.

Here, I am going to introduce you with asynchronous ado.net method which works asynchronously for any operation on database.

This article is describing the use of ExecuteScalar() method.

In ADO.NET 2.0 and higher versions, ADO.NET has enabled users to process database commands asynchronously. i.e. , we can now use a single connection for multiple, concurrent database access running them parallel

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/22/2013 2:21:12 PM