How to rename database in multi-user mode

China☆狼群 提交于 2020-01-11 17:54:05

问题


I am working on SQL SERVER 2008 & 2008 R2. How can I rename a database in multi-user mode? I am using sp_rename but it returns this error:

Msg 15225, Level 11, State 1, Procedure sp_rename, Line 338


回答1:


You can't rename a database while it is in use. Either wait for a maintenance window, or force the database to single user mode (which will kick everyone out):

USE [master];
GO
ALTER DATABASE foo SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
--EXEC sys.sp_renamedb @dbname = N'foo', @newname = N'bar';
ALTER DATABASE foo MODIFY NAME = bar; -- preferred way
GO
ALTER DATABASE bar SET MULTI_USER;



回答2:


You can't use sp_rename to rename a database - the sp in question would be sp_renamedb. However, that is in line to be removed in a future version of SQL Server and the preferred method is:

ALTER DATABASE dbname MODIFY NAME = newdbname;

But you can't do this anyway without an exclusive lock on the database.




回答3:


You can open sql server configuration manager and stop and start the service, this works for me with sql server 2008 and 2012 just fine.

Then rename the database right in the sql server management studio.

"Works for me"

Not really a "caveat" but say you want to restore the exact same database, you go into options and change the name of the mdf and ldf



来源:https://stackoverflow.com/questions/11014343/how-to-rename-database-in-multi-user-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!