0

以下は、2 つの部分からなるコードのセクションです。お互いにほぼ同じ。どちらもテーブルに何かを挿入してから、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 に答える