SqlCeParameter返回自动ID(主键)

Dev*_*ode 5 .net c# sql sql-server-ce sql-server-ce-4

我有一个SQL SqlCeParameter语句例如:

mySQLCommand1.CommandText = @"
   INSERT INTO clientSubjectiveComplaints (clientSubComplaintCreated)
   VALUES (@ClientSubComplaintCreated)
   ";
Run Code Online (Sandbox Code Playgroud)

一旦INSERT成功,我需要返回自动生成的ID(INT主键),以便我可以在第二个INSERT语句中使用它.

这可能SqlCe吗?如果你能提供一个例子,请.

Ale*_*Aza 7

像这样:

using (var connection = new SqlCeConnection(Settings.Default.Database1ConnectionString))
using (var command = connection.CreateCommand())
{
    connection.Open();

    command.CommandText = @"
        INSERT Test (Name)
        VALUES (@TestName)
        ";
    command.Parameters.AddWithValue("TestName", "SomeName");
    command.ExecuteNonQuery();

    command.CommandText = "SELECT @@IDENTITY";
    var id = command.ExecuteScalar();
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,如果你需要得到`int id`,最简单的方法就是这样做:'var id = Convert.ToInt32((decimal)command.ExecuteScalar());' (3认同)