将ID转换为Int并保存到数据表

本文关键字:保存 数据表 Int ID 转换 | 更新日期: 2023-09-27 18:27:57

我一直在尝试将Customer_ID从Customer表添加到Customer_Ship表中的Customer_ID。我一直遇到Customer_ID没有正确转换为Int。可能我实际上并没有首先将新行添加到Customer_Ship表中。非常感谢您的帮助,并提前表示感谢。

    if (customer_ID == "")
    {
    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 customer_Id = (int)sqlCommand.ExecuteScalar();
    SQL = "INSERT INTO Customer_Ship (Customer_ID) VALUES (@customer_Id)";
    sqlCommand = new SqlCommand(SQL, sqlConnection);
    sqlCommand.Parameters.AddwithValue("@customer_Id", customer_Id);
    sqlCommand.ExecuteNonQuery();
    sqlConnection.Close();
    }

将ID转换为Int并保存到数据表

我看到的两个错误:

  1. 您应该只返回SCOPE_IDENTITY-您可以将第一个INSERT语句简化为:

    INSERT INTO Customer (Customer_Name) VALUES (@customer_Name); SELECT SCOPE_IDENTITY();";
    

    Customer表返回新插入的Customer_ID标识值-无需执行问题中的复杂SELECT

  2. 您需要从一开始就调用.ExecuteScalar()-不要先调用.ExecuteNonQuery(),然后再调用ExecuteScalar()-这将执行两次语句-只需使用:

    using(SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection))
    {
         sqlCommand.Parameters.Add("@customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
         sqlConnection.Open();
         int customer_Id = (int)sqlCommand.ExecuteScalar();
         sqlConnection.Close();
    }
    

    这将把值插入到Customer中,并将新创建的Customer_ID作为返回值从.ExecuteScalar()返回到customer_id(它已经是Int)。然后,您可以使用这个int值插入到Customer_Ship表中——无需转换——这已经是一个int

不转换值的可能原因是您试图转换一个空字符串(customer_ID:请参阅代码的第1行),而不是从数据库中获取的内容。