Monday, October 12, 2009

Get the Identity of the record using ADO.NET

Suppose you require to get the IDENTITY of the record just after inserting it in Database,using ADO.NET, using ExecuteNonQuery() command. You want ur sql_storedprocedure not to return the IDENTITY. IN that case you need to write the code as below:

//C#
string employeeName="developer";
string query = "Insert Into Employees(EmployeeName) Values (?)";
string query2 = "Select @@Identity";

int ID;
string connect = "Data Source=(local);Initial Catalog=TestDB;User ID=sa;Password=sa123";
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("", employeeName);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}