sql-serverforeign-keysconstraintsdatabase-tabledrop-table

SQL DROP TABLE foreign key constraint


If I want to delete all the tables in my database like this, will it take care of the foreign key constraint? If not, how do I take care of that first?

GO
IF OBJECT_ID('dbo.[Course]','U') IS NOT NULL
    DROP TABLE dbo.[Course]
GO
IF OBJECT_ID('dbo.[Student]','U') IS NOT NULL
    DROP TABLE dbo.[Student]

Solution

  • No, this will not drop your table if there are indeed foreign keys referencing it.

    To get all foreign key relationships referencing your table, you could use this SQL (if you're on SQL Server 2005 and up):

    SELECT * 
    FROM sys.foreign_keys
    WHERE referenced_object_id = object_id('Student')
    

    and if there are any, with this statement here, you could create SQL statements to actually drop those FK relations:

    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('Student')