IMG-LOGO

How to delete all tables with specific prefix in one go using while loop in SQL Server?

andy - 04 Jan, 2014 2948 Views 0 Comment

You may wonder how you can delete all tables with specific prefix in a table in one go in SQL Server. It will save your time especially if you have hundred of tables rather than delete one by one, you can use the following script to do the easy job for you.

/*  Run this command in sql query panel, you just need to replace 'Prefix_TableName' to your prefix table' */
declare @query varchar(4000)
declare icursor cursor for
	Select 'drop table [' + Table_Name + ']'
	From    INFORMATION_SCHEMA.TABLES
	Where   Table_Name like 'Prefix_TableName%'
	union
	Select 'drop view [' + Table_Name + ']'
	From    INFORMATION_SCHEMA.VIEWS
	Where   Table_Name like 'Prefix_TableName%'
	open icursor
	while 1=1
	begin
		fetch icursor into @query
		if @@fetch_status != 0 break
		exec(@query)
	end
close icursor
deallocate icursor
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 ...