Link to home
Start Free TrialLog in
Avatar of AtulPadhye
AtulPadhye

asked on

Unable to truncate a table referenced by other tables using foreign keys

Table A has userid as a primary key, table B has userid as a primary key and references A.userid thru a foreign key, even if both tables are empty, I cannot truncate table A, why ?
I can delete table A by setting 'on delete cascade' option in the foreign key constraint, is
there a similar option for truncate ?
ASKER CERTIFIED SOLUTION
Avatar of Mark Geerlings
Mark Geerlings
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bbchang97
bbchang97

It won't allow u to delete the master records if child exists.  Since, without the master record, it's a violation for the forigen key constraints.

By using cascade delete, it's basically remove all child records related to the master row.

Ususally, if I'm trying to clean up both master and detail tables by using 'TRUNCATE' statement, I'll disable the foreign key ('ALTER TABLE XXX disable contraints FK_XXX'). I could then truncate both tables.  Afterwards, I could enable the foreign key again.

Hope this helps.
Hi,

As Delete handles row by row, it does with cascade option.
Truncate option handles on entire table. You should disable the foreign key constraint and try truncate.

Ashok.