SQL Server Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

SQL SELECT Database, USE Statement

Back to: SQL Server Tutorial

In Microsoft SQL Server, you can perform various tasks related to databases using SQL queries. Here's a brief overview of how you can list databases and use a specific database:

Listing Databases

To list all databases on your SQL Server instance, you can use the sys.databases system catalog view or the sp_databases stored procedure. Here are examples of both methods:

Using sys.databases:

SELECT name FROM sys.databases;

This query retrieves the names of all databases on the server.

Using sp_databases:

EXEC sp_databases;

This stored procedure returns a list of databases on the server.

Switching to a Specific Database

To switch to a different database within your session, you use the USE statement. The USE statement changes the context of your queries to the specified database. Here’s how you use it:

USE [DatabaseName];

Replace [DatabaseName] with the name of the database you want to use. For example:

USE [SalesDB];

After executing this command, any subsequent queries will be executed in the context of the SalesDB database.

Example Scenario

  1. List Databases:

    SELECT name FROM sys.databases;
  2. Switch to a Specific Database:

    USE [AdventureWorks];
  3. Run a Query in the New Database Context:

    SELECT TOP 10 * FROM [AdventureWorks].[dbo].[SalesOrderHeader];

Remember, you need appropriate permissions to switch to and query a database. If you encounter permission issues, make sure your user account has the necessary access rights to the database you’re trying to use.

Scroll to Top