Java |
Retrieve Identifier from database insert
I need to retrieve the identifier ID from an insert query so that I can associate it with another table. I'm using the scope_identity() method, but can't find out how to assign that to a variable so it can be used. So far I have:

Kirtan PatelRank #292 · 8.6K reputationPosted Oct 8, 2009, 4:24 AM EDT
Here is Simple One
SqlCommand comm = new SqlCommand("select IDENT_CURRENT('table1')", con);
int LastInsertedValue = Convert.ToInt32(comm.ExecuteScalar());
Or If your Column is Integral then You can Also Use Max to get Last value
SqlCommand comm = new SqlCommand("select max(id_column) from tablename", con);
int LastInsertedValue = Convert.ToInt32(comm.ExecuteScalar());
Rajeswari nathan97 reputationPosted Oct 8, 2009, 3:05 AM EDT
You can create one out put parameter in the SP and access the identity using that output parameter
Ben Gannaway12 reputationPosted Oct 8, 2009, 3:17 AM EDT
Rajeswari nathan97 reputationPosted Oct 8, 2009, 3:20 AM EDT
@ValueOut int OUTPUT
After inserting the data assign th identity in to that Out put parameter.
Like wise add one output parameter for the SP in C# code.
you can get the value..
as follows
aSqlServiceCommandL.Parameters.Add("@Ret", SqlDbType.Int);
aSqlServiceCommandL.Parameters["@Ret"].Direction = ParameterDirection.ReturnValue;
aSqlServiceCommandL.ExecuteNonQuery();
int nServiceIdL = (int)aSqlServiceCommandL.Parameters["@Ret"].Value;
Ben Gannaway12 reputationPosted Oct 8, 2009, 3:53 AM EDT
Ben Gannaway12 reputationPosted Oct 8, 2009, 4:12 AM EDT
int entryId; Console.WriteLine("Opening database"); SqlCommand myCommand = new SqlCommand("INSERT INTO entries(text, name, screen_name, user_id, posi_score)"+"VALUES(@txt,@nm,@scrNm,@uid,@posi_score)select scope_identity() as @identity", myConnection); myCommand.Parameters.AddWithValue("@txt", txt); myCommand.Parameters.AddWithValue("@nm", nm); myCommand.Parameters.AddWithValue("@scrNm", scrNm); myCommand.Parameters.AddWithValue("@uid", uid); myCommand.Parameters.AddWithValue("@posi_score",posiScore); myCommand.Parameters.Add("@identity", SqlDbType.Int); myCommand.Parameters["@identity"].Direction = ParameterDirection.ReturnValue; myConnection.Open(); myCommand.ExecuteNonQuery(); entryId = (int)myCommand.Parameters["@identity"].Value;But I'm getting a syntax error close to @identity
Ben Gannaway12 reputationPosted Oct 8, 2009, 6:01 AM EDT