Cannot truncate table ‘dbo.TableName’ because it is being referenced by a FOREIGN KEY constraint.
[:it]
Impossibile troncare una tabella quando vi è un vincolo di integrità referenziale
Spesso vi sarà capitato di ottenere il seguente messaggio di errore in SQL Server 2005 / 2008
Cannot truncate table ‘dbo.TableName’ because it is being referenced by a FOREIGN KEY constraint.
nel momento in cui avete tentato di eseguire una TRUNCATE TABLE.
Come si evince dal messaggio di errore il problema è dato dal fatto che la tabella sulla quale si sta cercando di effettuare una TRUNCATE contiene vincoli di integrità referenziale con altre tabelle.
L’unica soluzione per poter effettuare la TRUNCATE è:
- Effettuare la DROP delle CONSTRAINTS
- Effettuare la TRUNCATE
- Ricreare le CONSTRAINTS
possibilmente tutto in transazione.
Ecco uno snippet di esempio:
BEGIN TRANSACTION SET QUOTED_IDENTIFIER ON SET ARITHABORT ON SET NUMERIC_ROUNDABORT OFF SET CONCAT_NULL_YIELDS_NULL ON SET ANSI_NULLS ON SET ANSI_PADDING ON SET ANSI_WARNINGS ON COMMIT BEGIN TRANSACTION GO ALTER TABLE dbo.ChildTable DROP CONSTRAINT FK_ChildTable_ParentTable GO TRUNCATE TABLE dbo.ChildTable GO ALTER TABLE dbo.ChildTable ADD CONSTRAINT FK_ChildTable_ParentTable FOREIGN KEY ( IdParentOnChild ) REFERENCES dbo.ParentTable ( IdParent ) ON UPDATE NO ACTION ON DELETE NO ACTION GO COMMIT
[:en]
Impossibile troncare una tabella quando vi è un vincolo di integrità referenziale
Spesso vi sarà capitato di ottenere il seguente messaggio di errore in SQL Server 2005 / 2008
Cannot truncate table ‘dbo.TableName’ because it is being referenced by a FOREIGN KEY constraint.
nel momento in cui avete tentato di eseguire una TRUNCATE TABLE.
Come si evince dal messaggio di errore il problema è dato dal fatto che la tabella sulla quale si sta cercando di effettuare una TRUNCATE contiene vincoli di integrità referenziale con altre tabelle.
L’unica soluzione per poter effettuare la TRUNCATE è:
- Effettuare la DROP delle CONSTRAINTS
- Effettuare la TRUNCATE
- Ricreare le CONSTRAINTS
possibilmente tutto in transazione.
Ecco uno snippet di esempio:
BEGIN TRANSACTION SET QUOTED_IDENTIFIER ON SET ARITHABORT ON SET NUMERIC_ROUNDABORT OFF SET CONCAT_NULL_YIELDS_NULL ON SET ANSI_NULLS ON SET ANSI_PADDING ON SET ANSI_WARNINGS ON COMMIT BEGIN TRANSACTION GO ALTER TABLE dbo.ChildTable DROP CONSTRAINT FK_DETTAGLIORESIDUO_RESIDUI GO TRUNCATE TABLE dbo.ChildTable GO ALTER TABLE dbo.ChildTable ADD CONSTRAINT FK_ChildTable_ParentTable FOREIGN KEY ( IdParentOnChild ) REFERENCES dbo.ParentTable ( IdParent ) ON UPDATE NO ACTION ON DELETE NO ACTION GO COMMIT
[:]
Lascia un commento