SqlCeParameter return Auto ID (Primary Key)

余生长醉 提交于 2020-02-02 03:44:27

问题


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.


回答1:


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();
}



回答2:


ExecuteScalar("SELECT @@IDENTITY")

More details can be found here.



来源:https://stackoverflow.com/questions/6479949/sqlceparameter-return-auto-id-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!