读取最后插入的ID

时间:2014-10-26 01:27:58

标签: c# sql-server sql-server-2008

我已经完成了几周的工作,现在只能查找在数据库级别工作的语句。下面是我的代码,我觉得我非常接近答案,但继续从-1返回SCOPE_IDENTITY()Customer_Name随着自动增量一直保存到表中。我只需要Customer_ID,这样我就可以将它放在Customer_Address表中,以便为客户提供一对多的地址识别。

提前感谢您的帮助。

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();
}

2 个答案:

答案 0 :(得分:3)

您需要在与插入相同的事务中使用SCOPE_IDENTITY。以下内容对您有帮助。

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();

答案 1 :(得分:-1)

尝试这样的事情.. Output子句将帮助您获取插入的值,并且我们可以插入到另一个临时或物理表中。这只是你的问题的一个想法

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