Abdul Hannan Abdul Hannan - 1 year ago 104
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?

Answer Source

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'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download