2

When I try to truncate the table, i got the error Message as follows,

**Cannot truncate table 'Locations' because it is being referenced by a FOREIGN KEY constraint.**

I don't know the query for that..Anyone help me.

PoliDev
  • 1,408
  • 9
  • 24
  • 45
Duk
  • 905
  • 5
  • 15
  • 34

2 Answers2

1

Why?

The reason why is that TRUNCATE removes all the records without individual checking.

So a DELETE FROM Locations will delete each record (and that's what gets logged in the transaction logs), checking that no constraints have been violated.

TRUNCATE TABLE Locations doesn't do this. A single truncate action is performed (and logged) and this is why is is quicker.

See this article for more information.

Workaround

The easiest way is to delete rather than truncate. But if this has a long execution time, and it is safe to remove constraints, you might want to write a script to drop constraints, truncate table, create constraints.

Andy Nichols
  • 2,952
  • 2
  • 20
  • 36
1

One thing to be aware of - when you truncate the identity column is reset. When you delete it does not. So if you do a delete and the last value was 242, the next value will be 243.

The only way to do the truncate is to delete the relations. Personally - I would just delete instead of deleting all the relations and then putting them back.

Jeff B
  • 535
  • 1
  • 6
  • 15