I've got a method that deletes all data in a table however this wont work if there is a foreign key constraint. How do I check if there any reference constraints exist, delete those entriesfirst and then proceed to deleting all data in the specified table?
This is the exception thrown if there are any foreign key constraints:
"The DELETE statement conflicted with the REFERENCE constraint \"". The conflict occurred in database \"\", table \"\", column ''.\r\nThe statement has been terminated."}
Method:
public int DeleteFromDatabase(SqlConnection sqlConnection, string tableName)
{
int success = 0;
string sqlTrunc = "Delete from " + tableName;
if (isSafeSqlConnection(sqlConnection))
{
using (sqlConnection)
{
SqlCommand cmd = new SqlCommand(sqlTrunc, sqlConnection);
sqlConnection.Open();
success = cmd.ExecuteNonQuery(); //<-exception when constraint exists.
sqlConnection.Close();
}
}
return success;
}
What I need to know how to do is either: Drop constraint, delete constraint, reinstate constraint OR the better method being delete referenced constrainted data first and then proceed to deleting the table. Either way is ok for me.