Can not truncate table 'Table' because it is being referenced by a FOREIGN KEY constraint

0

Hi, I am trying to truncate ( TRUNCATE ) a database, but I have the problem that some tables are related so when I try to throw the query, it says:

  

Can not truncate table 'Table' because it is being referenced by a FOREIGN KEY constraint.

I found that I can disable relationships with:

SET FOREIGN_KEY_CHECKS = 0;

Apparently I have a syntax error? I need to remove ALL the information from the database (all tables) without altering their relationships. I am occupying SQL Server Management 2008

    
asked by E.Rawrdríguez.Ophanim 03.11.2017 в 17:34
source

1 answer

2

This response is a textual copy of: Is there a way to truncate table that has foreign to key?

You need to delete and recreate the keys, or wait for DELETE and re-fill them. Disabling the foreign key temporarily can make the DELETE faster, but it will continue without letting you do the truncate

ALTER TABLE [dbo].[tablename] NOCHECK CONSTRAINT ALL;

-- borrar, rellenar, etc.

ALTER TABLE [dbo].[tablename] WITH CHECK CHECK CONSTRAINT ALL;

The easy to automate this by building a dynamic SQL from the metadata tables, making it work exactly for the tables you need. For example, this will do so for each table that has a foreign key and a IDENTITY column:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SET NOCOUNT ON;';

;WITH s(t) AS
 (
   SELECT 
     QUOTENAME(OBJECT_SCHEMA_NAME(referenced_object_id)) 
     + '.' + QUOTENAME(OBJECT_NAME(referenced_object_id))
  FROM sys.foreign_keys AS k
  WHERE EXISTS 
  (
    SELECT 1 FROM sys.identity_columns 
    WHERE [object_id] = k.referenced_object_id
  )
  GROUP BY referenced_object_id
)
SELECT @sql = @sql + N'
  ALTER TABLE ' + t + ' NOCHECK CONSTRAINT ALL;
  DELETE ' + t + ';
  DBCC CHECKIDENT(''' + t + ''', RESEED, 0) WITH NO_INFOMSGS;
  ALTER TABLE ' + t + 'WITH CHECK CHECK CONSTRAINT ALL;'
FROM s;

PRINT @sql;
-- EXEC sp_executesql @sql;

The output may be truncated, but this is a limitation of the PRINT (8K), the current command is complete.

    
answered by 03.11.2017 / 18:23
source