0

I'm trying to rename my database but I'm not familiar with the syntax. I've tried 2 different things but get the following error msgs...

Method 1:

DECLARE @old varchar(100)
DECLARE @new varchar(100)
SET @old = 'ver.1'
SET @new = 'ver.2'

DECLARE @query varchar(max)
set @query = 'ALTER DATABASE @old MODIFY NAME = @new'
exec @query

Error: Could not find stored procedure 'ALTER DATABASE @old MODIFY NAME = @new'.


Method 2:

DECLARE @old varchar(100)
DECLARE @new varchar(100)
SET @old = 'ver.1'
SET @new = 'ver.2'

ALTER DATABASE @old MODIFY NAME = @new

Error: Incorrect syntax near @old

2 Answers 2

1

Stop using exec for dynamic SQL; use sp_executesql. Also, you can't inline parameterize arguments to ALTER DATABASE that way - you need to use string concatenation. Finally, because you chose to use illegal characters in your database name (.), you need to escape these with QUOTENAME.

DECLARE @old varchar(100) = 'ver.1';
DECLARE @new varchar(100) = 'ver.2';

DECLARE @query NVARCHAR(MAX) = N'ALTER DATABASE ' 
  + QUOTENAME(@old) + ' MODIFY NAME = ' + QUOTENAME(@new) + ';';

EXEC sp_executesql @query;
Sign up to request clarification or add additional context in comments.

Comments

0

We can also use sp_renamedb to rename database.

EXEC sp_renamedb 'old_name' , 'new_name'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.