0

I have 3000+ tables in my SQL 2008 database with names like listed below, that all starts with tempBinary_, that I need to delete programmatically, how do I do that? I don't know if I prefer the solution in a SQL-script or with use of LINQtoSQL, i guess both are fine.

tempBinary_002c90322f4e492795a0b8a14e2f7c99 tempBinary_0039f7db05a9456f96eb3cd6a788225a tempBinary_0057da9ef0d84017b3d0bbcbfb934fb2

I've used Like before on columns, but I don't know if it good for table names too. Maybe something like this, where LIKE is used, can do it? I don't know.

Use [dbo].[database_name]
DROP TABLE table_name
WHERE table_name LIKE 'tempBinary_%'

Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
radbyx
  • 9,352
  • 21
  • 84
  • 127
  • I think the solution might be close to this answer. http://stackoverflow.com/questions/4424038/how-to-delete-all-tables-with-prefix-bkp-from-a-given-database – radbyx Jul 04 '11 at 08:33
  • Cant do this in Linq2SQL, removed tag. – leppie Jul 04 '11 at 09:35

1 Answers1

2
declare @stmt varchar(max) = ''
declare @tbl_name varchar(255)


DECLARE tbl_cursor CURSOR  FORWARD_ONLY READ_ONLY
    FOR select name 
        from sysobjects 
        where xtype='u' and name like 'tempBinary%'
OPEN tbl_cursor
FETCH NEXT FROM tbl_cursor
INTO @tbl_name;

WHILE @@FETCH_STATUS = 0
BEGIN
    set @stmt = @stmt + 'drop table ' + @tbl_name + ';' +  CHAR(13)


    FETCH NEXT FROM tbl_cursor 
    INTO @tbl_name
end
CLOSE tbl_cursor;
DEALLOCATE tbl_cursor;    

execute sp_sqlexec @stmt
Adrian Iftode
  • 15,465
  • 4
  • 48
  • 73