views:

84

answers:

2

I have a table called PX_Child that has a foreign key on PX_Parent. I'd like to temporarily disable this FK constraint so that I can truncate PX_Parent. I'm not sure how this goes however.

I've tried these commands

ALTER TABLE PX_Child NOCHECK CONSTRAINT ALL

ALTER TABLE PX_Parent NOCHECK CONSTRAINT ALL

(truncate commands)

ALTER TABLE PX_Child CHECK CONSTRAINT ALL

ALTER TABLE PX_Parent CHECK CONSTRAINT ALL

But the truncate still tells me it can't truncate PX_Parent because of a foreign key constraint. I've looked all around the net and can't seem to find what I'm doing wrong, sorry for the basic nature of this question.

+3  A: 

You can't truncate the table if there is any foreign key referencing it, including disabled constraints. You either need to drop the foreign key constraints or use the DELETE command.

bobs
+1  A: 

SQL server will not let you truncate the table while the constraint exists, even if it's disabled. Drop the constraint and re-create it after truncating the table. Or just drop and re-create the tables, whichever is easier to do in your application.

pgroke
What do you mean it's not a transactional command? You can roll it back just fine. `CREATE TABLE Blah(a int); INSERT Blah VALUES(1); SELECT * FROM Blah; BEGIN TRAN; TRUNCATE TABLE Blah; SELECT * FROM Blah; ROLLBACK TRAN SELECT * FROM Blah; DROP TABLE Blah`. Truncate works by deallocating entire pages rather than removing rows, but it's still transactional.
Emtucifor
@Emtucifor: Oops, seems like I misinterpreted the documentation you you're right! I removed that piece of misinformation.
pgroke
@Emtucifor, @pgroke, in a way you are both correct as the standard allows for TRUNCATE to be non-transactional, but implementations are allowed to make it transaction. Hence TRUNCATE as defined doesn't promise a rollback can be done, but SqlServer (and Postgres) adds that promise beyond the standard.
Jon Hanna
@Jon Thanks for clarifying. Let me rephrase. **In SQL Server**, truncate is transactional.
Emtucifor