Osama Elfar
Osama Elfar

Reputation: 43

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

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

Upvotes: 4

Views: 2634

Answers (2)

Steve
Steve

Reputation: 216313

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

Upvotes: 8

Jürgen Gehrig
Jürgen Gehrig

Reputation: 1

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)

Upvotes: -1

Related Questions