snippetsqlMajor
How to drop multiple tables with common prefix in one query?
Viewed 0 times
tableswithquerydroponemultiplehowprefixcommon
Problem
I'm using Microsoft SQL Server 2008.My question is:How to drop multiple tables with common prefix in one query?
something like that table names:
something like that table names:
LG_001_01_STLINE,
LG_001_02_STFICHESolution
You can build up a string using the catalog views, e.g.:
Of course there are potential gotchas, for example if these tables have foreign key relationships, you'll either need to drop them first, or arrange the output to drop the tables in a certain order.
To just get the list of tables, use:
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += '
DROP TABLE '
+ QUOTENAME(s.name)
+ '.' + QUOTENAME(t.name) + ';'
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE t.name LIKE 'LG_001%';
PRINT @sql;
-- EXEC sp_executesql @sql;Of course there are potential gotchas, for example if these tables have foreign key relationships, you'll either need to drop them first, or arrange the output to drop the tables in a certain order.
To just get the list of tables, use:
SELECT s.name, t.name
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE t.name LIKE 'LG_001%';Code Snippets
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += '
DROP TABLE '
+ QUOTENAME(s.name)
+ '.' + QUOTENAME(t.name) + ';'
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE t.name LIKE 'LG_001%';
PRINT @sql;
-- EXEC sp_executesql @sql;SELECT s.name, t.name
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE t.name LIKE 'LG_001%';Context
StackExchange Database Administrators Q#5526, answer score: 36
Revisions (0)
No revisions yet.