Dropping and recreating databases in Microsoft SQL Server

后端 未结 6 1757
-上瘾入骨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条回答
  •  -上瘾入骨i
    2021-02-01 13:02

    +1 to AnandPhadke for his part of the code

    This code will close all active connections to the database and then drop it

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

提交回复
热议问题