0

looking for a simple way to check if a primary key already exists in the table before inserting into it. where Fname is the primary key in the table.

SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO [table] ([firstName], [lastName]) VALUES ('" + txtFName.Text + "','" + txtLName.Text + "')";        

cmd.ExecuteNonQuery();
conn.Close();

1 Answer 1

2

As a general rule, you should just try to insert. The dbms will return an error if they key exists. Trap that error.

You have to trap errors anyway, because there are a lot of things besides primary key constraints that can prevent a row from being inserted. Among them

  • Any other kind of constraint, like a foreign key constraint, a check constraint, etc.
  • Disk error.
  • Network error.
  • Hurricane.

You don't lose any efficiency by trapping the error.

  • Inserting (no error) requires one round-trip to the database.
  • Inserting (with error, which you trap) requires one round-trip to the database, not counting whatever you might have to do to correct that error. You'd have to do all the correcting if you checked first anyway.
  • Check-then-insert requires two round-trips to the database.

Some platforms can merge data if you try to insert a row for which a primary key already exists. The most famous (or most notorious, depending on your point of view) is MySQL's ON DUPLICATE KEY UPDATE.

1
  • 1
    One of my clients was a pilot plant. They had an explosion that threw bolts almost 20 miles. Another time, a diesel generator explosion killed power to about a square mile of downtown. So trap those errors. That's what I say. Commented Nov 1, 2012 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.