I need a function which executes an INSERT statement on a database and returns the Auto_Increment primary key. I have the following C# code but, while the INSERT statement w
As you're using Access, take a look at this article from aspfaq, scroll down to about half way down the page. The code's in classic ASP, but hopefully the principles should still stand.
The SELECT @@Identity ends up being treated as a separate execution context, I believe. Code that should work would be:
public int ExecuteInsertStatement(string statement)
{
InitializeAndOpenConnection();
IDbCommand cmdInsert = connection.CreateCommand();
cmdInsert.CommandText = statement + "; SELECT @@Identity";
object result = cmdInsert.ExecuteScalar();
if (object == DBNull.Value)
{
return -1;
}
else
{
return Convert.ToInt32(result);
}
}
You'd probably want/need to tidy up the concatenation that adds the 'SELECT @@Identity' onto the end of the code though.