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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With