Drop table with foreign key

2019-09-08 15:16发布

问题:

I'm trying this code

Drop Table Inventory

I get error:

Could not drop object 'Inventory' because it is referenced by a FOREIGN KEY constraint.

回答1:

First you have to Drop the table's constraints and then table

SELECT 
    'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '.[' + OBJECT_NAME(parent_object_id) + 
    '] DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Inventory')
Drop Table Inventory


回答2:

use this

DROP TABLE Inventory CASCADE CONSTRAINTS;


回答3:

You need to Drop the Constraint first..

ALTER TABLE [dbo].[t2] DROP CONSTRAINT [foreign key constraint]

then You can Drop the table

Drop table t1


回答4:

Just try this

ALTER TABLE Inventory NOCHECK CONSTRAINT all
DROP TABLE Inventory


回答5:

drop the foreign key constraint from subtable and then drop the main table