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
:
This query retrieves the names of all databases on the server.
Using 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:
Replace [DatabaseName]
with the name of the database you want to use. For example:
After executing this command, any subsequent queries will be executed in the context of the SalesDB
database.
Example Scenario
-
List Databases:
SELECT name FROM sys.databases; -
Switch to a Specific Database:
USE [AdventureWorks]; -
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.