SqlCeParameter返回自动ID(主键)

时间:2011-06-25 19:13:17

标签: c# .net sql sql-server-ce sql-server-ce-4

我有一个SQL SqlCeParameter语句,例如:

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

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

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

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:4)

ExecuteScalar("SELECT @@IDENTITY")

可以找到更多详细信息here

相关问题