Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all tables in SQL Server database except few

I have around 50+ table in my database now what I want is drop all the tables in database except few.

now what I know is sys.tables is a table that list all tables so initially I ran a query like this

delete from sys.tables where name like '%DynamicSurgery' (or any other condition)

thinking that it might work. But as I expected it throws an error as

Ad hoc updates to system catalogs are not allowed.

Please tell me if there is a way to delete multiples in SQL Server?

like image 366
Abdul Hannan Avatar asked Aug 02 '16 12:08

Abdul Hannan


1 Answers

You can use dynamic query to DROP the required tables:

DECLARE @ExecSQL AS NVARCHAR (MAX) = '';

SELECT @ExecSQL = @ExecSQL + 
    'DROP TABLE ' + QUOTENAME(S.name) + '.' + QUOTENAME(T.name) + '; ' 
FROM sys.tables T
JOIN sys.schemas S ON S.schema_id = T.schema_id
WHERE T.name LIKE '%DynamicSurgery'

--PRINT @ExecSQL
EXEC (@ExecSQL)
like image 100
Arulkumar Avatar answered Sep 23 '22 17:09

Arulkumar