简体   繁体   中英

Read Id of last inserted

I have been through everything for a couple weeks now only to find statements working at the database level. Below is my code and I feel that I am very near the answer but keep getting -1 returned from SCOPE_IDENTITY() . Customer_Name is saving to the table just fine along with the auto increment. I just need the Customer_ID so that I can place it in the Customer_Address table for the one to many identification of the address to the customer.

Thanks in advance for your help.

if (customer_ID == "")
{
    // add new customer
    string SQL = "INSERT INTO Customer (Customer_Name) VALUES (@customer_Name)";
    SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
    sqlCommand.Parameters.Add("@customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;

    // get last inserted Customer_ID
    string SQL_customerId = "SELECT SCOPE_IDENTITY()";
    SqlCommand sqlCommand_customerId = new SqlCommand(SQL_customerId, sqlConnection);

    sqlConnection.Open();
    sqlCommand.ExecuteNonQuery();
    sqlCommand_customerId.ExecuteNonQuery();

    // string SQL_ = "SELECT Customer_ID FROM Customer";
    // SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
    // int maxId = Convert.ToInt32(sqlCommand.ExecuteScalar());
    sqlConnection.Close();
}

You need to have the SCOPE_IDENTITY within the same transaction as your insert. The following should help you.

string SQL = "INSERT INTO Customer (Customer_Name) VALUES (@customer_Name); SELECT Customer_Id FROM Customer WHERE Customer_Id = SCOPE_IDENTITY();";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("@customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
sqlConnection.Open();
int id = (int) sqlCommand.ExecuteScalar();

try something like this.. Output clause will help you to get the inserted value and with that we can insert into another temp or physical table. This is just an idea to your question

CREATE TABLE customer
  (
     id     INT IDENTITY(1, 1),
     addres VARCHAR(500)
  )

CREATE TABLE customeraddrs
  (
     custid INT
  )

INSERT INTO customer
output      inserted.id
INTO customeraddrs
VALUES     ('a'),
            ('b')

SELECT *
FROM   customer

SELECT *
FROM   customeraddrs 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM