SqlCeParameter return Auto ID (Primary Key)

2019-05-01 01:30发布

I have an SQL SqlCeParameter statement for example:

mySQLCommand1.CommandText = @"
   INSERT INTO clientSubjectiveComplaints (clientSubComplaintCreated)
   VALUES (@ClientSubComplaintCreated)
   ";

Once the INSERT is successful I need the auto generated ID (INT Primary Key) returned so that I can use it in a second INSERT statement.

Is this possible for SqlCe ? Please if you can provide an example.

2条回答
迷人小祖宗
2楼-- · 2019-05-01 01:51
ExecuteScalar("SELECT @@IDENTITY")

More details can be found here.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-05-01 01:52

Like this:

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();
}
查看更多
登录 后发表回答