How to Avoid Duplicate Key Exception

Posted by LifeH2O on Stack Overflow See other posts from Stack Overflow or by LifeH2O
Published on 2010-06-17T13:26:03Z Indexed on 2010/06/17 13:33 UTC
Read the original article Hit count: 678

Filed under:
|
|
|

I am using TableAdapter to insert records in table within a loop.

foreach(....)
{
  ....
  ....
  teamsTableAdapter.Insert(_teamid, _teamname);
  ....
}

Where TeamID is the primary key in the table After first run of this loop, Insert throws Duplicate Primary Key found Exception. To handle this, i have done this

foreach(....)
{
  ....
  ....

  try
  {
     _teamsTableAdapter.Insert(_teamid, _teamname);
  }
  catch (System.Data.SqlClient.SqlException e)
  {
     if (e.Number != 2627)
        MessageBox.Show(e.Message);
  }
  ....
  ....
}

But using try catch statement is costly, how to avoid this exception. I am working in VS2010 and INSERT ... ON DUPLICATE KEY UPDATE does not work.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql