Dropping and recreating databases in Microsoft SQL Server

后端 未结 6 1912
-上瘾入骨i
-上瘾入骨i 2021-02-01 12:27

I am experimenting and learning with Microsoft SQL Server 2008 R2 SP1. I have a database where I made many experiments. Now I would like to drop and recreate it. So I extract th

6条回答
  •  眼角桃花
    2021-02-01 12:53

    Requiring the DBName to be typed more than once is error prone, at some point it'll be executed with inconsistent entries and unintended consequences.

    The answers from AnandPhadke or Pierre with variable support would be preferred for me.

    DECLARE @DBName varchar(50) = 'YourDatabaseName'
    USE master
    IF EXISTS(select * from sys.databases where name= @DBName)
    EXEC('DROP DATABASE ' + @DBName)
    
    EXEC('CREATE DATABASE ' + @DBName)
    

    or

    DECLARE @DBName varchar(50) = 'YourDatabaseName'
    WHILE EXISTS(select NULL from sys.databases where name = @DBName )
    BEGIN
        DECLARE @SQL varchar(max)
        SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';' FROM MASTER..SysProcesses WHERE DBId = DB_ID(@DBName) AND SPId <> @@SPId
        EXEC(@SQL)
        EXEC('DROP DATABASE ' + @DBName)
    END
    GO
    

提交回复
热议问题