There are two main ways to accomplish this:
- The use of USE
- Reference the database in your FROM statement
First, we can use the word USE. The general syntax for this is:
USE database
Where database is the database you are referencing. If our Customer table was in the Billing database, it would look something like this:
USE Billing
SELECT *
FROM Customer
Using USE leaves you rather limited, though, because only the one database can be referenced at a time using USE.
Our other option is to specify the database in our FROM statement. Let's say, for example, that we have our Customer table in the Billing database, while the Orders table is in the Shipping database. If we wanted to use both tables in the same query, it would look like this
SELECT *
FROM Billing.dbo.Customer
LEFT OUTER JOIN Shipping.dbo.Orders
on Customer.CustomerNumber = Orders.CustomerNumber
In the above, we put the database, a dot (.), the user (in this case dbo, which means database owner), another dot (.) and then the table name. Using this method, we can query multiple databases at the same time within the same query.
To read more on USE, go here: USE
To read more on selecting your database, go here: Select a Database