Please see my other Database Development articles.
Executing T-SQL against different databases
Often when accessing and manipulating data, requirements demand logic that crosses databases.
Performing such actions do not require drastically different T-SQL, only an understanding of the syntax.
In this example, I begin with two databases with identical tables and nearly identical records.
For simplicity, I’ve limited the resultset only to a few records to illustrate which records should remain when JOINing the tables.
As you can see below in my code, I’m performing a simple join.
However, what allows me to simultaneously access two different databases is prefacing each T-SQL statement with the name of the database, the object’s owner (dbo), and finally the name of the table.
Here are the results of the JOIN.
As you can see, only those record with identical PK values are returned.