私は通常、正しい scope_identity() 値を取得するために、レコードを挿入するときにストアド プロシージャを使用します。現在 SqlClient を使用している場合、挿入されたレコードの id フィールドを取得する必要があります。
私の理解では、scope_identity() コマンドを挿入でバッチ処理すると、挿入コマンドと同じスコープに残りますか? 以下のようなもの。確認するのは難しいですが...これで100%正しいID値を取得できますか..?
(id フィールドは自動インクリメント bigint - Sql Server)
long newid = 0;
using (SqlConnection conn = new SqlConnection(....))
{
conn.Open();
using (SqlCommand comm = new SqlCommand ("insert into .... ; select SCOPE_IDENTITY();", conn))
{
SqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
newid = Convert.ToInt64(reader[0]);
}
}
}