IMG-LOGO

How to delete all user creation tables in TSQL?

andy - 23 Dec, 2020 845 Views 0 Comment

If you need to delete all the user creation tables in TSQL. You can easily perform the deleting using the while loop against the sysobjects table.

The idea of the deletion is by declaring a variable name that will hold the table name and then we going to perform a select top 1 from the table name and perform deletion in the while loop while setting back the name to the next deletion table name until the table name is no longer found or equals to null.

Here is the full TSQL query code.


DECLARE @tableName VARCHAR(128)
DECLARE @SQL VARCHAR(500)

SELECT @tableName = (
	SELECT TOP 1 [name] FROM sysobjects 
	WHERE [type] = 'U' 
	AND category = 0 
	ORDER BY [name]
)

WHILE @tableName IS NOT NULL
	BEGIN
		SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@tableName) +']'
		EXEC (@SQL)
		PRINT 'Deleted Table: ' + @tableName
		SELECT @tableName = (
			SELECT TOP 1 [name] 
			FROM sysobjects 
			WHERE [type] = 'U' 
			AND category = 0 
			AND [name] > @tableName 
			ORDER BY [name]
		)
	END
GO

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to restore database using SQL query in TSQL?

If you have a database backup bak file extension and want to restore it using SQL query You can use the built in RESTORE DATABASE function Remember in order to be able to restore a database successfully You need to ...

How to get all table sizes in TSQL?

To get the information about how much space or size used by tables You can retrieve the size information by linking multiple tables in sys tables There are two tables that hold this information The first one is the sys ...