Abdul Hannan Abdul Hannan - 4 months ago 22
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

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?

Answer

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)
Comments