You must change your INSERT to return that inserted identifier to you right away (in the OUTPUT clause)! This works with SQL Server 2005 on - the OUTPUT clause is not available in SQL Server 2000 or earlier (you did not specify which version of SQL Server you are using in your question ..). Learn more about the OUTPUT clause in the MSDN online books .
Change your insert to something like:
INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN) OUTPUT Inserted.ID VALUES(Val1, Val2, ..., ValN);
and then when you execute the insert statement from C #, you should be able to:
using(SqlCommand cmdInsert = new SqlCommand("INSERT.....", myCon)) { myCon.Open(); var result = cmdInsert.ExecuteScalar(); myCon.Close(); }
and your result variable should now contain the correct, newly inserted value!
marc_s
source share