snippetsqlMajor
Why use master to create a database?
Viewed 0 times
whycreatedatabasemasteruse
Problem
I have a short question, why do I use
Here is the example from the Microsoft documentation
use master; to create a database?Here is the example from the Microsoft documentation
USE master ;
GO
CREATE DATABASE Sales
ON
( NAME = Sales_dat,
FILENAME = 'C:\Program Files\...\saledat.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = Sales_log,
FILENAME = 'C:\Program Files\...\salelog.ldf',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB ) ;Solution
It is absolutely not a requirement in this very specific case, but it is a requirement in many other scenarios. If you're creating a database called
There are plenty of other scenarios outside of database creation that also require either (a) not being in the context of the current database, or (b) being in the context of
Probably a slew of other things.
Sales, and you arelady have a database called Sales, you'll need to change your database context before you:- Restore with replace; or,
- Drop the current database and then:
- Create from scratch; or,
- Create for attach.
There are plenty of other scenarios outside of database creation that also require either (a) not being in the context of the current database, or (b) being in the context of
master specifically (or at least not a specific database), and many of these things you may be doing during or around creating databases:- Setting a database to a different state, like
single_user
- Preventing errors when a script has a
USEcommand but that user database may be offline or otherwise inaccessible
- Granting server-level permissions like
CREATE DATABASE
- Granting server-level role membership
- Marking a module as a system object (
sp_MS_marksystemobject) or as a startup procedure
- Certain types of certificate, server audit, and Availability Group operations
Probably a slew of other things.
USE master; isn't always necessary, but sometimes it is, and it doesn't hurt to always execute server-level commands from that database.Context
StackExchange Database Administrators Q#221191, answer score: 22
Revisions (0)
No revisions yet.