将ID转换为Int并保存到datatable

时间:2014-10-26 19:51:54

标签: c# .net sql-server

我一直在尝试将Customer表中的Customer_ID添加到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();
    }

2 个答案:

答案 0 :(得分:1)

我看到两个错误:

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

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

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

  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作为返回值返回customer_id(已经 一个{{1} } {}来自Int。然后,您可以使用此.ExecuteScalar()值插入int表格 - 无需转换 - 这已经是Customer_Ship

答案 1 :(得分:0)

不转换值的可能原因是您尝试转换空字符串( customer_ID :引用行:您的代码的第1行)而不是 &#34; customer_Id&#34; 您从数据库中提取的内容。