T-SQL: Cross-Database Logic

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.

cross-database-table-logic-table-views

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.

different-databases-logic-code

Here are the results of the JOIN.
As you can see, only those record with identical PK values are returned.

cross-database-cross-database-logic-results

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s