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:
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);
myConnection.Open(); myCommand.ExecuteNonQuery();
myConnection.Close(); Console.WriteLine("Closing database connection");
|
Kirtan PatelPosted Oct 8, 2009, 8:24 AM
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());
Ben GannawayPosted Oct 8, 2009, 10:01 AM
Ben GannawayPosted Oct 8, 2009, 8:12 AM
But I'm getting a syntax error close to @identity
Ben GannawayPosted Oct 8, 2009, 7:53 AM
Rajeswari nathanPosted Oct 8, 2009, 7:20 AM
@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 GannawayPosted Oct 8, 2009, 7:17 AM
Rajeswari nathanPosted Oct 8, 2009, 7:05 AM
You can create one out put parameter in the SP and access the identity using that output parameter