Cursor to Remove All Tables in Selected Database in SQL Server
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.
As you can see, all tables have been removed.
Good luck to everyone in business and life.