How to delete database, error 5030 database can't be locked

后端 未结 8 1384
自闭症患者
自闭症患者 2021-02-15 00:50

I am trying to delete an existing database in SQL Server 2005. My first attempt produced the following error:

5030: The database could not be exclusively

相关标签:
8条回答
  • 2021-02-15 01:46

    A production server in which so many connections use the database yet you want to drop it? :)

    None the less, how to kick out everybody from the database:

    USE [dbname];
    ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    

    Then drop the database:

    USE [master];
    DROP DATABASE [dbname];
    

    There is still a very small window of opportunity between the USE [master]; and DROP DATABASE ... where some other connection can grab the 1 single allowed lock on the database, but it usually not worth working around that.

    0 讨论(0)
  • 2021-02-15 01:54

    To avoid this error, use the T-SQL script below in the master database. Make sure to run this (and modify the @dbname) for each database you are running the ALTER DATABASE command in.

    "The database could not be exclusively locked to perform the operation"

    This "connection killer" script will work if Windows has established JDBC connections to the database. But this script is unable to kill off JDBC connections for Linux services (e.g. JBoss). So you'll still get that error if you don't stop JBoss manually. I haven't tried other protocols, but please comment if you find out more information as you build new systems.

    USE master;
    
    DECLARE @dbname sysname
    
    Set @dbname = 'DATABASE_NAME_HERE-PROD'
    
    Declare @spid int
    Select @spid = min(spid) from master.dbo.sysprocesses
    where dbid = db_id(@dbname)
    While @spid Is Not Null
    Begin
            Execute ('Kill ' + @spid)
            Select @spid = min(spid) from master.dbo.sysprocesses
            where dbid = db_id(@dbname) and spid > @spid
    End
    
    0 讨论(0)
提交回复
热议问题