Abdul Hannan Abdul Hannan - 6 months ago 34
SQL Question

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

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?


You can use dynamic query to DROP the required tables


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'