7

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?

2
  • 1
    Test and development site? Have a script to re-create the database. Start all over when needed. Commented Aug 2, 2016 at 12:21
  • 1
    You can write a cursor to iterate through sys.tables, where you build up drop table statements and execute them. Commented Aug 2, 2016 at 12:35

3 Answers 3

15

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)
Sign up to request clarification or add additional context in comments.

3 Comments

You must declare the variable as NVARCHAR because the table names may contain Unicode characters. You should make the @ExecSQL of length (MAX) because you do not know the number of tables (hence the length of the SQL). And you should use 2 part names QUOTENAME(schema) + '.' + QUOTENAME(name) because tables may belong to different schemas. And you must reference system tables and column by they correct names, including case, your example would fail on a case sensitive collation DB.
@RemusRusanu: Thanks for notifying. The said points are corrected.
Nice simple clean template for this type of problem. Thanks
1
            EXEC sys.sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL';

            EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN (
                  ISNULL(OBJECT_ID(''[dbo].[Table1]''),0),
                  ISNULL(OBJECT_ID(''[dbo].[Table2]''),0)
                  )
            DELETE FROM ?';

            EXEC sys.sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL';

Comments

-6
  1. select the table by clicking on it
  2. press the delete button and hit enter. Take note : if there is any dependencies(Foreign Key), the table will not be deleted

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.