Sql-server – To drop a table, do I have to drop all foreign key constraints or can I just NOCHECK them

foreign keysql server

I know you cannot drop a table that has active foreign key constraints.

So I was wondering is it safe to:

ALTER TABLE myTable NOCHECK CONSTRAINT all
DROP TABLE myTable

Rather than dropping the constraints first, table dropping:

ALTER TABLE myTable DROP Constraint FK_MyTable_AnotherTable
ALTER TABLE myTable DROP Constraint FK_MyTable_YetAnotherTable
DROP TABLE myTable 

Best Answer

SQL Server prevents you from dropping the table if a foreign key exists, nocheck or not:

create table t1
(id int not null, id2 int null)

create table t2
(id int primary key)

insert into t2 values (1)

insert into t1 values (1,1)

alter table t1 add constraint fk1 foreign key (id2) references t2(id)

alter table t1 nocheck constraint all

-- add a value to confirm nocheck working as expected
insert into t1 values (2,2)

-- lets clear out data from t1
truncate table t1

--alter table t1 drop constraint fk1

drop table t2

Gives you: Could not drop object 't2' because it is referenced by a FOREIGN KEY constraint.

So it's a moot point, really, you'll have to drop the FK first, either way.