下面是一段包含两部分的代码。几乎彼此相同。它们都将一些东西插入表中,然后调用Scope_identity。我已经检查确保插入了AddressType,它给了我CityId就好了。我看不出差异。我查看了代码,找不到我的错误。我希望有人可以成为额外的一双眼睛,并指出我确信,这肯定是一个明显的错误。
SqlCommand addressTypeCommand = new SqlCommand(
"INSERT INTO AddressType VALUES ('" + customerRow.AddressType + "');",
newCustConnection);
try
{
addressTypeCommand.ExecuteNonQuery();
}
catch (SqlException addressTypeException)
{
if (addressTypeException.ToString().StartsWith(
"Violation of UNIQUE KEY constraint"))
{
Console.WriteLine("Unique Key exception on 'AddressType'.");
}
}
SqlCommand selectAddressTypeID = new SqlCommand(
"select SCOPE_IDENTITY();", newCustConnection);
string addressTypeID = selectAddressTypeID.ExecuteScalar().ToString();
SqlCommand cityCommand = new SqlCommand(
"INSERT INTO City VALUES ('" + customerRow.City + "');",
newCustConnection);
try
{
cityCommand.ExecuteNonQuery();
}
catch (SqlException cityException)
{
if (cityException.ToString().StartsWith(
"Violation of UNIQUE KEY constraint"))
{
Console.WriteLine("Unique Key exception on 'City'.");
}
}
SqlCommand selectCityID = new SqlCommand(
"select SCOPE_IDENTITY();", newCustConnection);
string cityID = selectCityID.ExecuteScalar().ToString();
答案 0 :(得分:3)
要使用scope_identity()
,您需要与插入位于同一范围内。实现此目的的最简单方法是将其作为同一批次的一部分传递。
e.g。
SqlCommand addressTypeCommand = new SqlCommand(
"insert into AddressType values (@addressType); select scope_identity()"
);
addressTypeCommand.Parameters.AddWithValue(
// replace with correct datatype, possibly set data length
"@addressType", SqlDbType.VarChar, customerRow.AddressType
);
addressTypeID = addressTypeCommand.ExecuteScalar().ToString();