1
private void btnClear_Click(object sender, EventArgs e)
{
    int n;
    n = dgBooks.Rows.Count;

    if (n != 0)
    {
            string SqlText = "TRUNCATE TABLE [Books]";
            MyExecuteNonQuery(SqlText);
    }

}

MyExecuteNonQuery class sql command execution

Error:"Cannot truncate table 'Books' because it is being referenced by a FOREIGN KEY constraint."

mur0wilja
  • 11
  • 4
  • 1
    It's a SQL issue, not c# though – Jawad Dec 17 '19 at 16:36
  • 2
    This is a good example of the error message telling you exactly what the problem is. Some other table in your database has a foreign key to the table `books`. Look for tables with a field called `book_id`. – Dan Dec 17 '19 at 16:47
  • 2
    Does this answer your question? [Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?](https://stackoverflow.com/questions/253849/cannot-truncate-table-because-it-is-being-referenced-by-a-foreign-key-constraint) – Brydenr Dec 17 '19 at 17:51

2 Answers2

1

The foreign key constraint is telling your that at lease one other table has a relationship to your Books table. AKA you cannot truncate the Books table, other table(s) depend on it's data. You have to remove the foreign key constraint.

sspaniel
  • 647
  • 3
  • 10
  • 1
    Even if you truncate the other table, you still need to remove the constraint because the mechanism for checking the constraint is circumvented by `TRUNCATE`. – madreflection Dec 17 '19 at 16:39
0

You need to:

  1. DROP the foreign key constraint on the table. -

https://www.w3schools.com/sql/sql_ref_drop_constraint.asp

  1. TRUNCATE the table -

https://www.w3schools.com/sql/sql_ref_drop_table.asp

  1. Re-Add the FOREIGN KEY CONSTRAINT -

https://www.w3schools.com/sql/sql_foreignkey.asp

In that order

Vishav Premlall
  • 456
  • 6
  • 22