Rename a Database: #SQLNewBlogger

I had someone ask me how to rename a SQL Server database recently. They were doing some development work and wanted to rename databases to test an application. I thought I remembered, but in this post, I show I learned something.

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

Using sp_rename

I thought sp_rename would work, and sure enough, it did.

2024-10_0232

However, I need to object type. If I remove that parameter, it fails:

2024-10_0233

The command is looking for an object in the current database by default.

Technically, I ought to do this to be explicit, naming the parameters.

2024-10_0234

I have a better way, however. Note: it’s not sp_renamedb, which is marked for deprecation.

ALTER DATABASE

I don’t know when this changed, or if, but you can use ALTER DATABASE to change the database name. There is a MODIFY NAME option for this command that works well. You can see this below.

2024-10_0235

This is very clear and seems like better DDL For this process, which can easily be captured as code without worrying about parameters or ordering or anything else. I’d recommend using this.

SQL New Blogger

This post took me about 10 minutes to write. Easy. I had done a few experiments and I had code ready (which went to the customer), so I didn’t spend time there. Just rewrote what I did and learned in a few minutes.

You could do this, add to your blog, and maybe get an interviewer to ask you about this after they saw your post.

Unknown's avatar

About way0utwest

Editor, SQLServerCentral
This entry was posted in Blog and tagged , , . Bookmark the permalink.

1 Response to Rename a Database: #SQLNewBlogger

  1. Pingback: Renaming a Database in SQL Server – Curated SQL

Comments are closed.