I have the following function that executes an query and returns true on success and false on failure. No I wanted to extend the method so that with every insert query that is fired, the class var insertId contains the ID of the last inserted row.
The problem is that insertId is always 0, so somehow the executeScalar() is not returning the ID.
Any ideas? Or other solutions to get the ID of the last insert query….
public int insertId;
public bool executeCommand(string q) {
q += "; SELECT @@IDENTITY AS LastID";
bool retour = true;
SqlConnection myCon = new SqlConnection(Settings.DSN);
SqlCommand cmd = new SqlCommand(q, myCon);
try {
cmd.Connection.Open();
insertId = (int)cmd.ExecuteScalar();
if (insertId > 0) {
MessageBox.Show(insertId.ToString());
}
myCon.Close();
} catch (Exception ex) {
this.error = ex.Message;
retour = false;
}
return retour;
}
You should change your
INSERTto return that inserted ID to you right away (in anOUTPUTclause)! This works from SQL Server 2005 on – theOUTPUTclause isn’t available in SQL Server 2000 or earlier (you didn’t specify which version of SQL Server you’re using in your question…). Read more about theOUTPUTclause on MSDN Books Online.Change your insert to be something like:
and then when you execute your insert statement from C#, you should be able to do:
and your
resultvariable should now contain the proper, freshly inserted value!