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.