简体   繁体   English

插入SQL Server CE数据库文件并返回插入的id

[英]Inserting into SQL Server CE database file and return inserted id

Problem is : 问题是:

My query 我的查询

INSERT INTO TableName(val1,val2)values(1,2);
SELECT @@IDENTITY;

When I run it in run query from server explorer I get the correct result. 当我在服务器资源管理器的运行查询中运行它时,我得到了正确的结果。

But when I use ExecuteScalar or ExecuteDataTable I get an error ,... query return null 但是当我使用ExecuteScalarExecuteDataTable出现错误,...查询返回null

public object ExecuteScalre(string Query, CommandType type) 
{ 
    OpenConnection(); 
    cmd.CommandText = Query; 
    cmd.CommandType = type; 

    object obj = null; 

    try 
    { 
        obj = cmd.ExecuteScalar(); 
    } 
    catch 
    { 
    } 
    finally 
    { 
        ReleaseResource(); 
    } 

    return obj; 
} 

public DataTable ExecuteDataTable(string Query, CommandType type)
{
    OpenConnection();
    cmd.CommandText = Query;
    cmd.CommandType = type;
    DataTable dt = new DataTable();
    dataAdaptor = new SqlCeDataAdapter(cmd);

    try
    {
        dataAdaptor.Fill(dt);
    }
    catch
    {
    }
    finally
    {
        ReleaseResource();
    }
    return dt;
}

Notes: it's an .sdf file (SQL Server CE), NOT .mdf , so we can not use stored procedures 注意:它是一个.sdf文件(SQL Server CE),而不是 .mdf ,所以我们不能使用存储过程

Sql Server Compact Edition doesn't support multiple statements in one query. Sql Server Compact Edition在一个查询中不支持多个语句。
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. 此数据库(通常)在单个用户场景中使用,因此您可以拆分命令并向数据库发送两个查询,第一个插入记录,第二个返回@@ IDENTITY值。

    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. 这样做的原因是,您在一个Command对象中提交了两个sql命令。 The INSERT statement did return nothing, thats correct behavior. INSERT语句没有返回任何内容,这是正确的行为。
Use the OUTPUT -Clause of TSQL. 使用TSQL的OUTPUT -Clause。 This will give you values from inserted or deleted rows as a recordset. 这将为插入或删除的行提供值作为记录集。 So you can use ExecuteScalar to get this value. 因此,您可以使用ExecuteScalar来获取此值。

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 使用以下SQL为您提供作为结果集插入的行的ID

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM