Monday, August 16, 2010

SQL & ASP.net C# HELP : How to retrieve identity column value after inserting data into the table?

I am doing an asp.net using C# to program an application which accept user input and save into database then it requires approval. There is a colum in table that approved_or_not. So this purpose i created another page where admin can login to enter the id number which is generated by DB to approve or reject. So every time user input data and submit the application needs to send the identity colum nuber (PK) as an email to admin.SQL %26amp; ASP.net C# HELP : How to retrieve identity column value after inserting data into the table?
SqlConnection cn = new SqlConnection(SqlConnectionString);


SqlCommand cmd = cn.CreateCommand();





cmd.CommandText = ';INSERT INTO YourTable(FirstField, SecondField) VALUES (@FirstValue, @SecondValue); SELECT @Identity = SCOPE_IDENTITY(); ';;





cmd.Parameters.AddWithValue( ';@FirstValue'; , 3);


cmd.Parameters.AddWithValue( ';@LastValue'; , 6);





//the Identity parameter


SqlParameter prmIdentity = cmd.Parameters.AddWithValue(';@Identity';, SqlDbType.Int);


prmIdentity.Direction = ParameterDirection.Output;





//open the connection


cn.Open();





cmd.ExecuteNonQuery();





//retreive output parameter (ID)


int RetrievedPK = (int)prmIdentity.Value;





cn.Close();SQL %26amp; ASP.net C# HELP : How to retrieve identity column value after inserting data into the table?
http://cloudytech.blogspot.com鈥?/a>








see this tutorial its is helpfull 2 u

Report Abuse



You can use


SELECT SCOPE_IDENTITY()


after insert being done.

No comments:

Post a Comment