Inserting into SQL Server CE database file and return inserted id

断了今生、忘了曾经 提交于 2019-12-05 11:57:57

Sql Server Compact Edition doesn't support multiple statements in one query.
This database (usually) is employeed in a single user scenario, so you could split your command and send two queries to the database, the first inserts the record, the second one returns the @@IDENTITY value.

    cmd = new SqlCeCommand("INSERT INTO TableName(val1,val2)values(1,2)", cn);
    cmd.ExecuteNonQuery();
    cmd.CommandText = "SELECT @@IDENTITY";
    int result = Convert.ToInt32(cmd.ExecuteScalar());

The reason for this is the fact, that you submit two sql commands in one Command-object. The INSERT statement did return nothing, thats correct behavior.
Use the OUTPUT-Clause of TSQL. This will give you values from inserted or deleted rows as a recordset. So you can use ExecuteScalar to get this value.

Assume you have a table with the following structure

CREATE TABLE [dbo].[Table_1]  
([ID] [int] IDENTITY(1,1) NOT NULL,  
[Value1] [int] NOT NULL,  
[Value2] [int] NULL ) ON [PRIMARY]

Using the following SQL gives you the ID of the row inserted as a resultset

insert Table_1 OUTPUT Inserted.ID values (1,2)

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