Cursor to Remove All Primary Keys in Selected Database in SQL Server
Hello everyone,
In this article, I will give you information about removing all Primary Keys in the selected database in SQL Server with the help of Cursor.
In SQL Server you may need to remove all primary keys in some cases.
You can solve this operation in one go using the following query.
DECLARE @name VARCHAR(128);
DECLARE @constraint VARCHAR(254);
DECLARE @SQL VARCHAR(254);
SELECT @name =
(
SELECT TOP 1
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_CATALOG = DB_NAME()
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY TABLE_NAME
);
WHILE @name IS NOT NULL
BEGIN
SELECT @constraint =
(
SELECT TOP 1
CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_CATALOG = DB_NAME()
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_NAME = @name
ORDER BY CONSTRAINT_NAME
);
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) + '] DROP CONSTRAINT [' + RTRIM(@constraint) + ']';
EXEC (@SQL);
PRINT 'Kaldırılan Primary Key Constraintler : ' + @constraint + ' on ' + @name;
SELECT @constraint =
(
SELECT TOP 1
CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_CATALOG = DB_NAME()
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND CONSTRAINT_NAME <> @constraint
AND TABLE_NAME = @name
ORDER BY CONSTRAINT_NAME
);
END;
SELECT @name =
(
SELECT TOP 1
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_CATALOG = DB_NAME()
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY TABLE_NAME
);
END;
When you run the query, you will see an output like the one below.
As you can see, all foreign keys have been removed.
Good luck to everyone in business and life.