0

My initial concern was to DROP DATABASE MyDB when a certain condition is met but I get this error:

Database 'MyDB' is still in use

So, the answer I found was to do

USE master 
DROP DATABASE MyDB

It works, but for my case there is no guarantee whether master will be the default database on the server or not.

I would like to know how do I get the default database name for that particular server so that I can write something like

USE Default_DB 
DROP DATABASE MyDB
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Lelouch
  • 37
  • 4
  • 2
    `master` will always be there for any SQL Server instance - it's one of the four pre-defined, pre-created and **must have** databases on any SQL Server instance. I think doing a `USE master` is always safe. – marc_s Aug 25 '21 at 05:07
  • Was your question answered? – Mitch Wheat Sep 16 '21 at 02:12

1 Answers1

1

The default database is set per login, not for the server. If not specified when creating a login, it defaults to 'master'.

You change it like this:

ALTER LOGIN [user_name] WITH DEFAULT_DATABASE = [default_database]

Ref: CREATE LOGIN

To answer your actual question, you should always move to 'master' to delete a database:

USE master
GO

DROP DATABASE MyDB
GO
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541