Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 766
Osama Elfar Avatar asked Mar 19 '23 10:03

Osama Elfar


1 Answers

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());
like image 161
Steve Avatar answered Apr 26 '23 15:04

Steve