Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I drop a table if there is a foreign key constraint in SQL Server?

Tags:

sql-server

I have the following:

DROP TABLE [dbo].[ExtraUserInformation]; DROP TABLE [dbo].[UserProfile]; DROP TABLE [dbo].[webpages_Membership]; DROP TABLE [dbo].[webpages_OAuthMembership]; DROP TABLE [dbo].[webpages_Roles]; DROP TABLE [dbo].[webpages_UsersInRoles];  CREATE TABLE [dbo].[ExtraUserInformation] (     [Id]       INT            IDENTITY (1, 1) NOT NULL,     [UserId]   INT            NOT NULL,     [FullName] NVARCHAR (MAX) NULL,     [Link]     NVARCHAR (MAX) NULL,     [Verified] BIT            NULL,     CONSTRAINT [PK_dbo.ExtraUserInformation] PRIMARY KEY CLUSTERED ([Id] ASC) );  CREATE TABLE [dbo].[webpages_UsersInRoles] (     [UserId] INT NOT NULL,     [RoleId] INT NOT NULL,     PRIMARY KEY CLUSTERED ([UserId] ASC, [RoleId] ASC),     CONSTRAINT [fk_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserProfile] ([UserId]),     CONSTRAINT [fk_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[webpages_Roles] ([RoleId]) ); 

However this is failing with a message saying:

Msg 3726, Level 16, State 1, Line 6 Could not drop object 'dbo.UserProfile' because it is referenced by a FOREIGN KEY constraint. Msg 3726, Level 16, State 1, Line 9 Could not drop object 'dbo.webpages_Roles' because it is referenced by a FOREIGN KEY constraint. Msg 2714, Level 16, State 6, Line 27 There is already an object named 'UserProfile' in the database. Checking identity information: current identity value 'NULL', current column value 'NULL'. DBCC execution completed. If DBCC printed error messages, contact your system administrator. 

How can I drop a table in these circumstances?

like image 655
Samantha J T Star Avatar asked Feb 27 '13 08:02

Samantha J T Star


People also ask

Does dropping a table drop foreign key constraint?

Dropping Tables/Schemas/Databases For example, when dropping a database, if the database contains a primary/unique key which is referenced by a foreign key from another database, the referencing foreign keys are also dropped.

How do you drop a table that contains referential constraints?

To drop foreign key (referential) constraints, use the DROP CONSTRAINT clause of the ALTER TABLE statement. When a foreign key constraint is dropped, packages or cached dynamic statements containing the following might be marked as invalid: Statements that insert or update the table containing the foreign key.


1 Answers

You must drop the constraint before you can drop the table. Otherwise its rule violation that could break the databases Referential Integrity.

How to get foreign key relationships see this old question. SQL DROP TABLE foreign key constraint

like image 60
4b0 Avatar answered Sep 24 '22 03:09

4b0