How to drop a SQL Server database?

今天做数据库实验遇到一个问题—建立的数据库删除不了!问题错误提示如下:

Cannot drop database " DatabaseName " because it is currently in use.寻思了好久,加上在网上搜索资料才解决了。现将与dropa SQL Server database相关的知识记录如下:


The easy answer is to issue the following command in Query Analyzer: 
 

DROP DATABASE 数据库名

 
However, you will sometimes receive the following error: 
 

Server: Msg 3702, Level 16, State 3, Line 1 
Cannot drop the database '数据库名' because it is currently in use.

 
Hopefully you aren't in the habit of trying to drop production databases; so,more often than not, this error occurs because your current Query Analyzerwindow is actually set to the context of 数据库名. So, I usually recommend gettingrid of extraneous Query Analyzer windows, and using the following commandinstead: 
 

USE MASTER 
GO 
 
DROP DATABASE 数据库名

 
You might still get the error, if other users are connected without yourknowledge. One way to get rid of them immediately: 
 

ALTER DATABASE 数据库名 
    SET SINGLE_USER 
    WITH ROLLBACK IMMEDIATE

 
This will drop kick any connections and roll back their transactions, at whichpoint you should be able to drop the database successfully. 
 
However, this leaves out SQL Server 7.0 users, who don't have access to such acommand. Here is a stored procedure I created for 7.0: 
 

CREATE PROCEDURE dbo.clearDBUsers 
    @dbName SYSNAME 
AS 
BEGIN 
    SET NOCOUNT ON 
 
    DECLARE @spid INT, 
        @cnt INT, 
        @sql VARCHAR(255) 
 
    SELECT @spid = MIN(spid), @cnt = COUNT(*) 
        FROM master..sysprocesses 
        WHERE dbid = DB_ID(@dbname) 
        AND spid != @@SPID 
 
    PRINT 'Starting to KILL '+RTRIM(@cnt)+' processes.' 
     
    WHILE @spid IS NOT NULL 
    BEGIN 
        PRINT 'About to KILL '+RTRIM(@spid) 
 
        SET @sql = 'KILL '+RTRIM(@spid) 
        EXEC(@sql) 
 
        SELECT @spid = MIN(spid), @cnt = COUNT(*) 
            FROM master..sysprocesses 
            WHERE dbid = DB_ID(@dbname) 
            AND spid != @@SPID 
 
        PRINT RTRIM(@cnt)+' processes remain.' 
    END 
END 
GO

 
Sample usage: 
 

EXEC dbo.clearDBUsers '数据库名'

 
You might have to call the procedure multiple times before it completes theprocess of wiping out existing users. 
 
And because it happens so often, I'm going to suggest again: please make surethat your current Query Analyzer window isn't the elusive process that won't goaway! Make sure you are using the Master database when trying to drop userdatabases!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值