how to avoid duplicate ids to store in database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rekhasc
    New Member
    • Oct 2007
    • 66

    how to avoid duplicate ids to store in database

    hi friends...

    i am inserting Employee id to database through form...
    how to find that the id is already there in the database.. if its already present then one message should come .. and the Emp id should not store in the database...
    how to do this

    i am using sql server 2005, C# and Asp.net

    i have assigned the primary key to Emp Id...
    but i also want to write a code in the application
  • kunal pawar
    Contributor
    • Oct 2007
    • 297

    #2
    I suppose not need to do more. Coz ur field is primary so it not allowed to insert duplicate ID record.

    When u try to insert duplicate ID it throws exception. U hv to catch it and display message.
    duplicate key not allowed

    Comment

    • cloud255
      Recognized Expert Contributor
      • Jun 2008
      • 427

      #3
      If you want to do it in code you need to select all the IDs from your table when the user clicks to submit.

      Store these IDs in a datastructure, somethine like a binary search tree or hash table, then search for the ID the user has entered, if it is found show an error message. If it is not found simply perform the INSERT SQL command.

      Comment

      • adityakoppolu
        New Member
        • Sep 2008
        • 17

        #4
        Write a condition like this before saving

        DataTable dt = new DataTable();

        execute that query like
        " select Emp Id form table whre Emp Id=' Collect it form textbox control' "

        save the data in 'dt' table


        if(dt.rows.coun t > 0 )
        error message "ID already exist
        else
        Write the remaining logic for insertion

        Comment

        • rekhasc
          New Member
          • Oct 2007
          • 66

          #5
          Originally posted by adityakoppolu
          Write a condition like this before saving

          DataTable dt = new DataTable();

          execute that query like
          " select Emp Id form table whre Emp Id=' Collect it form textbox control' "

          save the data in 'dt' table


          if(dt.rows.coun t > 0 )
          error message "ID already exist
          else
          Write the remaining logic for insertion



          Thank for your replys....
          actually i am taking the id from one table that displays in datagrid and inserting to other table.. while inserting to other table it should not take the duplicate values

          Comment

          Working...