我一直在尝试将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();
}
答案 0 :(得分:1)
我看到两个错误:
您应该返回SCOPE_IDENTITY
- 您可以将第一个INSERT
语句简化为:
INSERT INTO Customer (Customer_Name) VALUES (@customer_Name); SELECT SCOPE_IDENTITY();";
将从Customer_ID
表格中返回新插入的Customer
标识值 - 无需执行问题中的复杂SELECT
< / p>
您需要从头开始调用.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; 您从数据库中提取的内容。