DECLARE @t
table
(
spid int
)
INSERT INTO @t
SELECT spid FROM sys.sysprocesses AS p
WHERE EXISTS
(
SELECT * FROM sys.databases
WHERE name = '旧数据库名称'
AND p.dbid = database_id
)
DECLARE @spid int
DECLARE @ sql nvarchar( max)
WHILE(( SELECT COUNT(*) FROM @t) > 0)
BEGIN
SELECT TOP 1 @spid=spid FROM @t
SET @ sql = 'kill ' + CAST(@spid AS varchar(100))
EXEC sp_executesql @ sql
DELETE FROM @t WHERE spid = @spid
END
GO
EXEC sp_dboption '旧数据库名称', 'single user', 'true'
GO
EXEC sp_renamedb '旧数据库名称', '新数据库名称'
GO
EXEC sp_dboption '新数据库名称', 'single user', 'false'
GO
(
spid int
)
INSERT INTO @t
SELECT spid FROM sys.sysprocesses AS p
WHERE EXISTS
(
SELECT * FROM sys.databases
WHERE name = '旧数据库名称'
AND p.dbid = database_id
)
DECLARE @spid int
DECLARE @ sql nvarchar( max)
WHILE(( SELECT COUNT(*) FROM @t) > 0)
BEGIN
SELECT TOP 1 @spid=spid FROM @t
SET @ sql = 'kill ' + CAST(@spid AS varchar(100))
EXEC sp_executesql @ sql
DELETE FROM @t WHERE spid = @spid
END
GO
EXEC sp_dboption '旧数据库名称', 'single user', 'true'
GO
EXEC sp_renamedb '旧数据库名称', '新数据库名称'
GO
EXEC sp_dboption '新数据库名称', 'single user', 'false'
GO