0

下面是一段包含两部分的代码。几乎一模一样。他们都在表中插入一些东西,然后调用 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();
4

1 回答 1

3

要使用scope_identity(),您需要在与插入相同的范围内。实现这一点的最简单方法是将其作为同一批次的一部分传递。

例如

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();
于 2013-11-16T21:57:47.853 回答