Mark Uy

Mark Uy

  • NA
  • 130
  • 0

how to immediately retrieve the identify after insert

Dec 4 2009 3:13 PM
i have a button that inserts a record to an invoice table and InvID is the name of its identity primary key.

  protected void txtSaveInvoice_Click(object sender, EventArgs e)
{
SqlConnection conInvoice3 = new SqlConnection
(@"Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\TRANE.mdf;Integrated Security=True;User Instance=True");
conInvoice3.Open();

string saveInvoice;

saveInvoice = "INSERT INTO Invoice(EmpID, UnitList, CustomerID, InvoicePrice, Datetime, Comment) Values ('" + UserLabel.Text + "', '" + Label2.Text + "', '" + txtCust.Text + "', '" + Label4.Text + "', '" + LabelDate.Text + "', '" + txtRemark.Text + "') SET @InvID = SCOPE_IDENTITY()";

SqlCommand cmdInvoice = new SqlCommand(saveInvoice, conInvoice3);


cmdInvoice.ExecuteNonQuery();

Response.Redirect("invoice_redirect.aspx");
conInvoice3.Close();

}

googling around i found an article that mentions "scope identity". but the layout of his code is a bit different since im using a very noobish concatenated approach.

my question is how do i integrate a scope identity and display its value on a label?

thanks in advance

Answers (1)