The USE Database Statement in SQL Server

The USE [database] command in SQL Server is used to switch the context to a specific database when running queries. This is useful when you need to work with multiple databases or change the active database during a session.

When to use this statement:
– When you want to execute queries on a different database than your default one, without including 3 part identifier (databaseName.schemaName.tableName).
– To switch between databases during a query execution session.

How it Works in SQL Server Management Studio (SSMS):
When you log into SQL Server using SSMS, your database context is automatically set to your default database, which is assigned during the creation of your SQL login.
– If you open a new query window (using the shortcut Ctrl + N), your query will be scoped to the default database.

To change the database context, you can either:
Select the database from the drop-down menu in SSMS.
Run the USE [database] command in your query window.

Use Database Example

-- Use database example sql server
USE [animals];
GO;
Use Database SQL
SQL Use Example

Note: The USE command does not work with Azure SQL Database. Azure SQL uses a different method for database switching, which typically involves connecting to the correct database in the connection string.

If you don’t know the names of the available databases, and they aren’t visible in the SSMS Object Explorer, you can query the sys.databases system catalog view to get a list of all databases.

Hope this was useful info for you. Feel free to browse around, click an internal link you see around you for more random SQL Server DBA tips!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *