如何在SQL中修改/重命名数据库名称?

问题描述 投票:0回答:3

如何在SQL中修改/重命名数据库名称?

运行以下脚本会抛出异常“@dbname 附近的语法不正确”

Declare @dbname nvarchar(50)
set @dbname = 'MyDatabase_Test'

ALTER DATABASE MyDatabase MODIFY NAME = @dbname;
sql sql-server t-sql
3个回答
5
投票
DECLARE @SQLString nvarchar(500);  
DECLARE @OldDbName nvarchar(100);
DECLARE @NewDbName nvarchar(100);

SET @OldDbName =  'MyTestDatabase';
SET @NewDbName =  'MyNewTestDatabase';
BEGIN TRY

        SET @SQLString =  
                    N'ALTER DATABASE ' +  @OldDbName + ' SET SINGLE_USER WITH ROLLBACK 
IMMEDIATE'; 
        EXECUTE sp_executesql @SQLString

        SET @SQLString =  
                    N'ALTER DATABASE ' +  @OldDbName + ' MODIFY NAME = ' + @NewDbName;
        EXECUTE sp_executesql @SQLString            

        SET @SQLString =  
                    N'ALTER DATABASE ' +  @NewDbName + ' SET MULTI_USER' ;
        EXECUTE sp_executesql @SQLString

END TRY
BEGIN CATCH
    PRINT ERROR_MESSAGE();

END CATCH 

4
投票

您必须将其作为动态 SQL 来执行。

Declare @dbname nvarchar(50)
set @dbname = 'MyDatabase_Test'

EXEC('ALTER DATABASE MyDatabase MODIFY NAME = ' + @dbname);

0
投票
USE master;

去 更改数据库 MyTestDatabase 设置 SINGLE_USER 并立即回滚; 去 更改数据库 MyTestDatabase 修改名称 = MyTestDatabaseCopy; 去 更改数据库 MyTestDatabaseCopy 设置 MULTI_USER; 去吧

© www.soinside.com 2019 - 2024. All rights reserved.