Problem: Suppose we have a situation where we need to drop those tables that have some prefixes string, so it is possible to drop those tables with a common prefix in a single query.
Solution: yes it is possible to drop all those tables that have the common prefix in a single query. Using following query you can delete all those tables that begin with a certain prefix string. In where condition just put the common prefix string in where condition (Like ‘prefix%’)
DECLARE@queryNVARCHAR(MAX)=N''; SELECT@query+=' DROP TABLE ' +QUOTENAME(s.name) +'.'+QUOTENAME(t.name)+';' FROMsys.tablesASt INNERJOINsys.schemasASs ONt.[schema_id]=s.[schema_id] WHEREt.nameLIKE'MX_100%'; EXECsp_executesql@query; |
This query may create an issue, if a table has a foreign key relationship, you'll either need to drop them first or arrange the output to drop the tables in a certain order.
If you want to monitor exactly what goes on when the query is running then use the following query.
DECLARE@queryvarchar(4000) DECLAREcsrCURSORFOR SELECT'drop table ['+Table_Name+']' FROMINFORMATION_SCHEMA.TABLES WHERETable_NameLIKE'<prefix>%' OPENcsr WHILE 1 = 1 BEGIN FETCHcsrINTO@query IF@@fetch_status!= 0 BREAK EXEC@query) END CLOSEcsr; DEALLOCATEcsr |
Note: If you are not a Database developer then don’t use above query contact to your database department.