Disable constraints and truncate table

  • Hi,

     

    I am trying to disable constraints, truncate table and re-enable the constraints, but I am still getting the following error

    'Cannot truncate table 'owner' because it is being referenced by a FOREIGN KEY constraint.' any idea?

    Thanks

  • You'll have to delete the data in the child tables before deleting the parent table's data (even truncate can't go around this).

    What's the problem you're trying to solve by this task?

  • Delete is taking for ever, I am trying to use truncate instead to increase the performance and truncating the parent table after truncate the child table but still getting the error.

  • If you just want to wipe out both tables, you can disable or delete the foreign key, then you'll be able to truncate both tables.

    Here's out to disable / enable the fk :

    --disable

    ALTER TABLE TableName NOCHECK CONSTRAINT FkName

    -- Reenable

    ALTER TABLE TableName CHECK CONSTRAINT FkName

  • That’s exactly what I am doing, but still getting error

  • Script the foreign key, drop it, truncate, recreate foreign key... I was under the impression that it was possible to do it without dropping the relation.. but apparently it is not.

    Can anyone else elaborate on this??

  • Thanks Remi

  • Prabhakar,

    Here is a script I am using in a DTS package:

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblBuildingAlias_tblBuildingName]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)

    ALTER TABLE [dbo].[tblBuildingAlias] DROP CONSTRAINT FK_tblBuildingAlias_tblBuildingName

     

    just modify it with the appropriate names and you should be set.

     

    Good luck,

    Darrell

  • While you are dropping the FK Constraints, you my want to check if you also have indexes on the tables that you are about to import into.  After the import is successful, script the re-creation of you indexes as well.  This saves a ton of time and helps keep your log file smaller if you are importing a large amount of data into tables withn complex indexes.

    -Mike Gercevich

  • Thanks guys!

  • Remi,

    TRUNCATE won't work if a table is referenced by a foreign key constraint, even if the constraint is disabled.  BOL is kind of vague about this, but I've experienced it.  I always use the 'drop fk, truncate, load, create fk' method in DTS.

    Greg

    Greg

  • Ya I reread up on this, and in the disable section of the constraint, they referrence only updates and inserts as affected operations... so I guess truncate/delete is out of the question, which makes sens when you think about it.

Viewing 12 posts - 1 through 11 (of 11 total)

You must be logged in to reply to this topic. Login to reply