Cursor to Remove All Tables in Selected Database in SQL Server

Hello everyone,

In this article, I will give you information about removing all Tables in the selected database in SQL Server with the help of Cursor.

In SQL Server, in some cases, all tables in the database may need to be removed.

You can solve this operation in one go using the following query.

DECLARE @name VARCHAR(128);
DECLARE @SQL VARCHAR(254);
SELECT @name =
(
    SELECT TOP 1
           [name]
    FROM sysobjects
    WHERE [type] = 'U'
          AND category = 0
    ORDER BY [name]
);
WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) + ']';
    EXEC (@SQL);
    PRINT 'Kaldırılan Tablolar : ' + @name;
    SELECT @name =
    (
        SELECT TOP 1
               [name]
        FROM sysobjects
        WHERE [type] = 'U'
              AND category = 0
              AND [name] > @name
        ORDER BY [name]
    );
END;

When you run the query, you will see an output like the one below.

Cursor to Remove All Tables in Selected Database in SQL Server

As you can see, all tables have been removed.

Good luck to everyone in business and life.

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