Hi,
I want to get newly inserted ID after inserting data in table. I am using command object's ExecuteNonQuery. I don't want to use MAX in another query. Is there any way to do. I am using ad-hoc query not a storedprocedure. Also i don't want to use @@identy because it is a global variable and at the same time if any other insert statement fires the value of @@Identy
Thanks in Advance.....
Mahseh...

How i get new ID after inserting data in table through command.ExecuteNonQuery
Max Andre Bundchen
Subi
You can also use the scope_identity() method if you're using Sql Server. There's a subtle difference between @@identity and scope_identity(), so I'll refer to the Sql Server books online if you want to know what the difference is.
redplanet
thanks David...
AleXXus
thanks Frederik,
Actuly my issue is how can i get those value through execuetnonquery with the insert statement. For @@Identy i have to fire another query to DB which i don't want.
Davettttttttttttttttt
You can look at this other message in this forum for the answer:
http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=236419&SiteID=1
Here is an example from the other message that uses SCOPE_IDENTITY() to get the recently added identity value :
str = "Insert INTO TblAccount(Name) VALUES (@Name) Set @AccountNumber = SCOPE_IDENTITY()";
SqlParameter[] sqlParams = new SqlParameters[2];
sqlParams[0] = new SqlParameter("@Name", SqlDbType.Char);
sqlParams[0].Value = "whatever";
sqlParams[1] = new SqlParams("@AccountNumber",...);
sqlParams[1].Direction = ParameterDirection.Output;
...
cm.ExecuteNonQuery();
int accountNumber = (int)sqlParams[1].Value; // assuming integer
I wrote a post in my blog about this because the question gets asked so often:
Retrieve Identity Column Value After Inserting Record in Database Table
Hope this helps,
Dave