How to Remove All Foreign Keys from All Tables in SQL Server?

Hello everyone,

In this article, I will provide information on how to remove all Foreign Keys in all tables in SQL Server.

In SQL Server in some cases you may want to remove all Foreign Keys from all tables.

You can easily do this using the code below.

DECLARE @Command VARCHAR(MAX)
DECLARE curCommand CURSOR FOR
SELECT 
	'ALTER TABLE ' + OBJECT_NAME(fk.parent_object_id) + ' DROP CONSTRAINT [' + RTRIM(fk.Name) + '];'
FROM sys.foreign_keys fk

OPEN curCommand

FETCH NEXT FROM curCommand INTO @Command

WHILE @@FETCH_STATUS = 0
BEGIN

	EXEC(@Command)

    FETCH NEXT FROM curCommand INTO @Command
END

CLOSE curCommand
DEALLOCATE curCommand

As soon as you run the above code in the relevant database, all Foreign Keys will be removed.

Note: You are responsible for the transaction.

Good luck to everyone in business and life.

181 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!