我有一个删除表中所有数据的方法,但是如果存在外键约束,这将不起作用。如何检查是否存在任何引用约束,首先删除这些条目,然后继续删除指定表中的所有数据?
如果存在任何外键约束,则抛出此异常:
{"The DELETE statement conflicted with the REFERENCE constraint \"". The conflict occurred in database \"\", table \"\", column ''.\r\nThe statement has been terminated."}
方法:
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;
}
我需要知道的是:删除约束,删除约束,恢复约束或更好的方法是先删除引用的约束数据,然后继续删除表。无论哪种方式都适合我。
答案 0 :(得分:0)
您有几个选择:
maxTuplesPending
然后首先删除该外键表中的所有行。请参阅How can I list all foreign keys referencing a given table in SQL Server?