如何在SQL中修改/重命名数据库名称?
运行以下脚本会抛出异常“@dbname 附近的语法不正确”
Declare @dbname nvarchar(50)
set @dbname = 'MyDatabase_Test'
ALTER DATABASE MyDatabase MODIFY NAME = @dbname;
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
您必须将其作为动态 SQL 来执行。
Declare @dbname nvarchar(50)
set @dbname = 'MyDatabase_Test'
EXEC('ALTER DATABASE MyDatabase MODIFY NAME = ' + @dbname);
USE master;
去 更改数据库 MyTestDatabase 设置 SINGLE_USER 并立即回滚; 去 更改数据库 MyTestDatabase 修改名称 = MyTestDatabaseCopy; 去 更改数据库 MyTestDatabaseCopy 设置 MULTI_USER; 去吧