如何在SQL中修改/重命名数据库名称?
运行以下脚本将引发异常,因为“ @dbname附近的语法不正确”
Declare @dbname nvarchar(50)
set @dbname = 'MyDatabase_Test'
ALTER DATABASE MyDatabase MODIFY NAME = @dbname;
答案 0 :(得分:1)
您必须将其作为动态SQL进行。
Declare @dbname nvarchar(50)
set @dbname = 'MyDatabase_Test'
EXEC('ALTER DATABASE MyDatabase MODIFY NAME = ' + @dbname);
答案 1 :(得分:1)
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