开发者

Delete all tables with a certain prefix name in a SQL 2008 database programmatically

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_n开发者_开发百科ame
WHERE table_name LIKE 'tempBinary_%'

Any ideas?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜