How to auto increment field value after inserting to database?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Formula
    New Member
    • Aug 2008
    • 11

    How to auto increment field value after inserting to database?

    Hi, i'm working on my first project on asp.net using c#.

    I'm adding a couble of fields to database but i need the primary key of the master table to add it to sub table.


    The database contains 2 tables :


    Question Table :questionID(pri mary key and identity) , questionInText

    Answer table : answerID , answer1,answer2 , questionID


    code used to insert to db :
    Code:
     string strInsert = "Insert INTO question(questionInText)Values(@questionInText)";
    
            cmdInsert = new SqlCommand(strInsert , conn);  
     
            cmdInsert .Parameters.AddWithValue("questionInText", txtQuestion.Text);
    
            cmdInsert.ExecuteNonQuery();
    questionID is auto increment.

    The question is : How i get questionID after adding to database without using sql statment ?

    please help.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    In this case you want to retrieve the Identity that was given to the record when it was added to the Question Table.

    To do this you need to use the @@IDENTITY system function. It returns the last-inserted identity value.

    Please note that in this case the ExecuteNonQuery method is not a good choice since the SQL statement will be returning a value. You should be using the ExecuteReader method instead.

    Comment

    Working...