How to select data of a table from another database in SQL Server?
To query a table from a different database in SQL Server, adopts the three-part naming convention: [DatabaseName].[SchemaName].[TableName]
. Example: query data from table Employee
within HR
database.
Here, HR
represents the destination database, dbo
indicates the default schema, and Employee
is the target table.
More details: Navigating Diverse Databases
Operating within multiple databases on a single server or journeying across servers, SQL Server extends several approaches to navigate these tasks effectively.
Cross-server query with Linked Servers
Assuming the databases are residing on diverse servers, sp_addlinkedserver
is enlisted to set up linked servers. You can now run the queries as if you're working on your local server, just like a universal remote to the server universe.
Post establishing the linked server, your SQL query turns into an international passport:
For instance, accessing "testdb" on the "test server" from your current "proddb" on the "prod server":
Direct database queries in SQL Server 2012+
In SQL Server 2012 and beyond, direct querying to a different database, all on the same server, is as simple as pie. The three-part naming serves the need just right, it's a no-brainer even without initiating linked servers:
The Security Corner: Cross-database Considerations
When working with cross-database or cross-server inquiries, waving the security flag becomes elemental to maintain data confidentiality and integrity. Involve appropriate permissions and also mind the ownership chaining for secure chit-chat with the data environment.
Scaling up: Querying from a linked server
On few occasions, the requirement so steps up that linking to a remote server becomes inevitable. Fear not, your query structure is just a bit modified, not rocket science.
Linked server setup:
First off, grab the credentials, then set up the linked server:
Query execution:
Post successful completion, summon the tables from the remote server:
Ensure to replace all placeholders with the actuals — ServerNickname
, databaseWhereabouts
, schemaLocation
, and tableAddress
, they're waiting for you!
Quid pro quo — Synonyms for quicker queries
In SQL Server, synonyms offer the ease of referring to often-used tables from disparate databases or servers. It's like a nickname for lengthy table addresses:
Now index it further simply by:
Was this article helpful?