HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Changing database context before creating new database

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
beforenewcreatingdatabasecontextchanging

Problem

I have noticed on many examples that before CREATE DATABASE statement, there is part that changes database context.

USE master;
GO

CREATE DATABASE Sample;
GO


I wonder why is that because with or without it, in SQL Server Management Studio 17, database creates right where it is supposed to be.

Solution

Often these examples are accompanied by (or are expected to be copied and pasted to a script with) other commands, such as a DROP DATABASE first (which can’t happen if you’re in the context of that database that you’re trying to drop and re-create).

There are a few commands that need to be run in master, but not a whole ton. This may just be a convention by habit rather than by reason, and in all honesty, it probably is the source of many mistaken deployments to master instead of a user database. I wrote a tip about this situation:

  • Cleaning up the SQL Server master database

Context

StackExchange Database Administrators Q#204740, answer score: 8

Revisions (0)

No revisions yet.