Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
hi,

I have Lot tables Starts with Certain Names like tblEMi% and i want to drop it it one Shot in SQL Server 2005

Pls Help

Regards
Nirmala
Posted
Comments

 
Share this answer
 
Comments
Maciej Los 12-Oct-14 12:29pm    
5ed!
Mehdi Gholam 12-Oct-14 12:48pm    
Cheers Maciej!
Use this ..


SQL
drop table from sys.tables where name like 'tblEMi%'




if Not Done than use below code.


SQL
DECLARE @id varchar(200) 
DECLARE @drop varchar(150)
DECLARE @namingPattern varchar(150) 
set @namingPattern = 'tblEMi%'

DECLARE myCursor CURSOR FOR 
    SELECT name FROM sys.tables WHERE name like @namingPattern 

OPEN myCursor 
FETCH next FROM myCursor INTO @id 

WHILE @@fetch_status=0 
BEGIN 
	
    SET @drop = N'drop table ' + @id 
   
    EXECUTE(@drop) 
    
  
    FETCH next FROM myCursor INTO @id 
END 

CLOSE myCursor 
DEALLOCATE myCursor



Thanks
AARIF SHAIKH
 
Share this answer
 
Hi Nirmala, before dropping all the tables, you might need to delete all the relations between them or perhaps you need to delete those tables in a proper order. So you can get the list of the all the tables from the below query.
SQL
SELECT sySchema.name, sysTab.name FROM sys.tables AS sysTab INNER JOIN sys.schemas AS sySchema 
  ON sysTab.[schema_id] = sySchema.[schema_id] WHERE sysTab.name LIKE 'tblEMi%';


So once you are happy with the table names, you can run the below query to provide you the scripts to drop the tables.

SQL
DECLARE @sqlQry NVARCHAR(MAX) = '';
SELECT @sqlQry += 'DROP TABLE ' + QUOTENAME(sySchema.name) + '.' + QUOTENAME(sysTab.name) + ';'
    FROM sys.tables AS sysTab INNER JOIN sys.schemas AS sySchema ON sysTab.[schema_id] = sySchema.[schema_id]
    WHERE sysTab.name LIKE 'tblEMi%';
SELECT @sqlQry;
 
Share this answer
 
/* Drop Tables With Certain Prefixes */
declare @cmd varchar(4000)
declare cmds cursor for
select 'drop table [' + Table_Name + ']'
from INFORMATION_SCHEMA.TABLES
where Table_Name like 'prefix%'

open cmds
while 1=1
begin
fetch cmds into @cmd
if @@fetch_status != 0 break
exec(@cmd)
end
close cmds;
deallocate cmds
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900