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.

Cursor to Remove All Primary Keys in Selected Database in SQL Server

As you can see, all foreign keys have been removed.

Good luck to everyone in business and life.

133 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!