T-SQL 101: #30 Changing databases with the USE statement in T-SQL

Take a look at the following query:

I've asked for a list of the databases from the sys.databases view. But rather than executing it against whichever database I was already connected to, I've said USE master; to change to the master database.

The command will be sent to the master database instead of any other database that I might have been connected to. At that point, master becomes my "current database".

Then by saying USE PopkornKraze; I've asked SQL Server to change to working with the PopkornKraze database. The commands that execute after that USE statement will be sent to the server, with PopkornKraze as the current database.

Did I need to change?

If you look at the third query, I've used a three part name to refer to the view in the master database. So even though the command will be sent with the PopkornKraze database as the current database, I'm referring to a view in the master database.

Learning T-SQL

It's worth your while becoming proficient in SQL. If you'd like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.

Leave a Reply

Your email address will not be published.