sql server 分离附加数据库

时间:2021-12-20 03:43:01
/********------分离数据库-----------**********/
--------单步执行-----------
--
(1)
SELECT spid,loginame,dbid FROM sysprocesses
WHERE dbid=DB_ID('ReportServer')
--(2)kill掉某个访问连接
KILL 54
--(3)分离数据库
EXEC sp_detach_db @dbname='ReportServer'

--由于一个数据库由很多进程连接,一个一个kill掉进程显然不适用,下面用存储批量kill进程来分离数据库
--
----使用T-SQL执行-------------
--
(1)创建存储过程
USE master
GO
CREATE PROC Detachdb(@dbname varchar(max) )
AS
BEGIN
DECLARE @Spid INT
DECLARE Cursorid CURSOR FOR SELECT spid FROM sysprocesses WHERE dbid=DB_ID(@dbname)
OPEN Cursorid
FETCH NEXT FROM Cursorid INTO @Spid
WHILE @@fetch_status!=-1
BEGIN
EXEC ('KILL '+@Spid)--注意kill后面加空格
FETCH next FROM Cursorid INTO @Spid
END
CLOSE Cursorid
DEALLOCATE Cursorid
--执行分离数据库
EXEC sp_detach_db @dbname=@dbname
END

--(2)调用存储过程分离数据库ReportServer
USE master
GO
DECLARE @database VARCHAR(max)='ReportServer'
EXEC Detachdb @database
GO
--附加数据库 (注意是否有辅助文件)---
USE master
GO
EXEC sp_attach_db @dbname='ReportServer',
@filename1='C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\ReportServer.mdf',
@filename2='C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\ReportServer_log.ldf'
GO