2014-07-01

Handling auto-generated Identity fields in asp.net using ExecuteScalar

http://www.mikesdotnetting.com/Article/54/Getting-the-identity-of-the-most-recently-added-record

Getting the identity of the most recently added record


The built-in functions @@Identity and Scope_Identity() are designed to retrieve the most recently added record's autoincrement identity value from Access and Sql Server respectively. Here are some examples.(click on link above)

//C#
string query = "Insert Into Categories (CategoryName) Values (@CategoryName);" +
"Select Scope_Identity()";
int ID;
string connect = @"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Northwind.mdf;" +
    "Database=Northwind;Trusted_Connection=Yes;";
using (SqlConnection conn = new SqlConnection(connect))
{
  using (SqlCommand cmd = new SqlCommand(query, conn))
  {
    cmd.Parameters.AddWithValue("@CategoryName", Category.Text);
    conn.Open();
    ID = (int)cmd.ExecuteScalar();
  }
}

No comments:

Post a Comment

Github CoPilot Alternatives (VSCode extensions)

https://www.tabnine.com/blog/github-copilot-alternatives/