How to drop multiple databases in SQL Server

后端 未结 3 1647
梦如初夏
梦如初夏 2020-12-24 02:19

Just to clarify, ths isn\'t really a question, more some help for people like me who were looking for an answer.
A lot of applications create temp tables and the like, b

相关标签:
3条回答
  • 2020-12-24 02:52

    There is no need to use a cursor, and no need to copy and paste SQL statements. Just run these two lines:

    DECLARE @Sql as NVARCHAR(MAX) = (SELECT 'DROP DATABASE ['+ name + ']; ' FROM sys.databases WHERE name LIKE 'DBName%' FOR XML PATH(''))

    EXEC sys.sp_executesql @Sql

    Of course, any DB matching the criteria will be dropped immediately, so be sure that you know what you are doing.

    0 讨论(0)
  • 2020-12-24 03:01

    Why not just do this instead?

    USE master;
    Go
    SELECT 'DROP DATABASE ['+ name + ']' 
    FROM sys.databases WHERE name like '_database_name_%';
    GO
    

    Capture the output of that resultset and then paste it into another query window. Then run that. Why write all this TSQL cursor code?

    "When you have a hammer, everything looks like a nail!"..

    0 讨论(0)
  • 2020-12-24 03:02

    this is easy...

    use master
    go
    declare @dbnames nvarchar(max)
    declare @statement nvarchar(max)
    set @dbnames = ''
    set @statement = ''
    select @dbnames = @dbnames + ',[' + name + ']' from sys.databases where name like 'name.of.db%'
    if len(@dbnames) = 0
        begin
        print 'no databases to drop'
        end
    else
        begin
        set @statement = 'drop database ' + substring(@dbnames, 2, len(@dbnames))
        print @statement
        exec sp_executesql @statement
        end
    
    0 讨论(0)
提交回复
热议问题