Linked Server

A complete guide to configuring, using and troubleshooting Linked Servers in SQL Server to integrate data from different sources.

Hi everyone! As an old friend of SQL Server, I know we often need to integrate data that lives on different servers. That’s where the Linked Server comes in, acting as a solid bridge between separate data environments. In this post, we’ll go deep into Linked Servers, from basic setup to advanced tips and troubleshooting. Get ready to see everything this tool can do!


What Is a Linked Server and Why Do You Need One?

Imagine you have sales data on one server and customer information on another. Or maybe your main system runs on an older SQL Server, but you need to pull data from a financial system running on a newer instance, or even on Oracle, DB2 or MySQL. A Linked Server is exactly what you need!

In simple terms, a Linked Server is a SQL Server setting that lets one SQL Server instance run commands against another OLE DB data source. That data source can be another SQL Server instance (local or remote), Oracle, MySQL, DB2, and even an Excel or CSV file (yes, you read that right!). It works as a “shortcut” to external data, making it possible to run queries, updates and even create objects on remote servers, all from your local instance.

But why use a Linked Server? There are plenty of reasons:

  • Data Integration: Bring together data from different sources for reports, analysis or migrations.
  • Distributed Queries: Run queries that span multiple servers without having to move the data.
  • ETL Processes (Extract, Transform, Load): Make it easier to extract and load data between systems.
  • Centralized Management: Access data from different environments through a single interface.
  • Less Network Traffic: In some scenarios, it can be more efficient to query the data on the source server than to transfer large volumes.

Hands-On: Configuring a Linked Server

Setting up a Linked Server can look intimidating at first, but I promise it’s simpler than it seems. Let’s go step by step, both in SQL Server Management Studio (SSMS) and with T-SQL.

Using SQL Server Management Studio (SSMS)

This is the most visual and intuitive way if you’re just getting started:

  1. Connect with SSMS: Open SQL Server Management Studio and connect to the instance where you want to create the Linked Server.
  2. Go to “Server Objects”: In Object Explorer, expand “Server Objects”.
  3. Expand “Linked Servers”: Inside “Server Objects”, expand “Linked Servers”.
  4. New Linked Server: Right-click “Linked Servers” and select “New Linked Server…”.
  5. Fill in the Information: A new “New Linked Server” window opens. This is where the magic happens.
    • General Page:
      • Linked server: Give your Linked Server a meaningful name. This is the name you’ll use in your queries (e.g. MEU_SERVER_REMOTO).
      • Server type:
        • SQL Server: If you’re connecting to another SQL Server instance, select this option.
        • Other data source: For other data sources (Oracle, MySQL, Excel, etc.), select this one and choose the appropriate OLE DB provider. For SQL Server, this option is more generic and lets you specify the provider and connection string manually.
      • Product name: For SQL Server, we usually fill in “SQL Server”. For others, the product name (e.g. “Oracle”).
      • Data source: The name or IP address of the remote server. If it’s a named instance (e.g. SEUSQL\INSTANCIA), use SEUSQL\INSTANCIA.
      • Provider string: Leave it blank for standard SQL Server. Other providers may need extra connection parameters.
      • Catalog: The default database name on the remote server for this Linked Server. Optional, but useful.
    • Security Page: This one is crucial for authentication.
      • Not be made: No security context. Not recommended for most scenarios.
      • Be made using the login’s current security context: Authentication uses the credentials of the user running the query on the local server. Useful in domain environments with integrated Windows authentication.
      • Be made using a security context that the login’s current security context does not support: For users that aren’t mapped.
      • Be made using this security context: This is the most common and flexible option. You specify a remote login (user and password) that will be used to access the linked server.
        • Remote login: The user name on the remote server.
        • With password: The password for the remote user.
      • Add: Map specific local server logins to specific remote server logins. Very useful for fine-grained security.
    • Server Options Page:
      • Collation Compatible: If the servers have different collation settings and you need the Linked Server to handle that.
      • Data Access: Enables or disables data access.
      • RPC, RPC Out: Allow remote procedure calls. Essential for running remote stored procedures.
      • Use Remote Collation: Uses the remote server’s collation.
  6. Click OK: Your Linked Server is ready!

Using T-SQL (Transact-SQL)

If you prefer automation and full control, T-SQL is the way to go. The basic syntax is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
EXEC sp_addlinkedserver
    @server = 'MEU_SERVER_REMOTO', -- Linked Server name
    @srvproduct = 'SQL Server',      -- Remote server product (e.g. 'SQL Server', 'Oracle')
    @provider = 'SQLNCLI11',         -- OLE DB provider (SQLNCLI11 for SQL Server 2012 and later, SQLOLEDB for older versions)
    @datasrc = 'NOME_OU_IP_DO_SERVER_REMOTO\INSTANCIA_REMOTO'; -- Data source (server name or IP, with instance if applicable)

EXEC sp_addlinkedsrvlogin
    @rmtsrvname = 'MEU_SERVER_REMOTO', -- Linked Server name
    @useself = 'FALSE',               -- 'TRUE' to use the current security context, 'FALSE' to specify a login
    @locallogin = NULL,               -- Local login (NULL for all local logins)
    @rmtuser = 'usuario_remoto',      -- Remote login
    @rmtpassword = 'sua_senha_secreta'; -- Remote login password

Important notes:

  • @provider: For SQL Server, SQLNCLI11 is the recommended provider for SQL Server 2012 and later. For older versions (up to SQL Server 2008 R2), SQLOLEDB was the default. Make sure the provider is installed and registered.
  • @locallogin: If you want only one specific login on your local server to be able to use this Linked Server, replace NULL with the local login name. Otherwise, NULL lets any local login use the mapping.
  • sp_addlinkedsrvlogin: You can call sp_addlinkedsrvlogin multiple times to map different local logins to different remote logins, or to map local logins to the current security context (@useself = 'TRUE').

Testing and Using Your Linked Server

Once it’s configured, it’s time to test!

Querying Data

The most common way to use a Linked Server is through four-part name queries:

1
2
3
4
5
6
7
SELECT *
FROM MEU_SERVER_REMOTO.NomeDoBancoDeDados.NomeDoSchema.NomeDaTabela;

-- Real example:
SELECT c.NomeCliente, p.NomeProduto
FROM MEU_SERVER_REMOTO.VendasDB.dbo.Clientes c
INNER JOIN SEGUNDO_SERVER.EstoqueDB.dbo.Produtos p ON c.ProdutoID = p.ProdutoID;

You can also use the OPENQUERY function for more complex queries or to improve performance, because it sends the query straight to the remote server to be executed there, not on the local server.

1
2
SELECT *
FROM OPENQUERY(MEU_SERVER_REMOTO, 'SELECT ClienteID, NomeCliente FROM VendasDB.dbo.Clientes WHERE DataRegistro > GETDATE() - 30');

The OPENDATASOURCE function is similar, but it lets you specify the data source ad hoc, without a preconfigured Linked Server. Use it with care, because it’s less secure and more verbose.

1
2
3
SELECT *
FROM OPENDATASOURCE('SQLNCLI11', 'Data Source=NOME_OU_IP_DO_SERVER_REMOTO\INSTANCIA_REMOTO;Initial Catalog=VendasDB;User ID=usuario_remoto;Password=sua_senha_secreta')
.VendasDB.dbo.Clientes;

Running Remote Stored Procedures

Yes, you can! This is really useful for orchestrating processes across different servers.

1
EXEC MEU_SERVER_REMOTO.NomeDoBancoDeDados.dbo.MinhaStoredProcedureRemota @Parametro1 = 'Valor';

Managing and Troubleshooting Common Problems

Even SQL Server experts run into challenges with Linked Servers. Here are some important points and troubleshooting tips:

Security

Security comes first.

  • Principle of Least Privilege: Grant only the permissions the remote login needs. Don’t use sa or accounts with excessive privileges.
  • Windows vs. SQL Server Authentication: Windows authentication is more secure, especially in domain environments. If you use SQL Server authentication, make sure passwords are strong and rotated regularly.
  • Login Mapping: Use sp_addlinkedsrvlogin to map local logins to specific remote logins, for finer-grained security.

Performance

Linked Server queries can be slower because of network latency and the query optimizer.

  • OPENQUERY: Use OPENQUERY whenever possible. It “pushes” the query to the remote server, minimizing network traffic and taking advantage of the source server’s query optimizer.
  • Indexes: Make sure the tables you’re querying on the remote server have appropriate indexes.
  • Simple Queries: Avoid complex queries or massive JOINs across servers if you can. Pull only the data you need.
  • Data Transfer: For large data volumes, consider replication, SSIS or other ETL tools instead of direct Linked Server queries.

Common Troubleshooting

  • “Login failed for user…”: The most common error. Check the user name and password configured in sp_addlinkedsrvlogin (or on the Security tab in SSMS). Make sure the remote user has permission to access the required database and tables.
  • “OLE DB provider ‘SQLNCLI11’ for linked server ‘…’ returned message ‘No process is on the other end of the pipe.’”: Usually points to a network connectivity problem (a firewall blocking port 1433), the SQL Server service on the remote server being stopped, or an incorrect server/instance name.
  • “The OLE DB provider ‘SQLNCLI11’ for linked server ‘…’ reported an error. Access denied.”: The remote user has access to the server, but not permission for the specific action (SELECT, INSERT, UPDATE, DELETE) on the table/view you’re trying to access.
  • “Cannot initialize the data source object of OLE DB provider ‘…’ for linked server ‘…’”: A problem with the OLE DB provider. It may not be installed or registered correctly, or the connection string is wrong.
  • Timeout Errors: Queries that take too long to respond can be cut off by timeouts. Adjust the Linked Server timeout settings in the server options (Server Options -> Connection Timeout, Query Timeout) or with sp_serveroption.

Dropping a Linked Server

If you need to remove a Linked Server:

1
EXEC sp_dropserver 'MEU_SERVER_REMOTO', 'droplogins';

The 'droplogins' argument makes sure the associated login mappings are removed too.


Final Thoughts and Next Steps

The Linked Server is a powerful and versatile tool in any DBA’s or SQL Server developer’s toolkit. With it, you can build solid data integration solutions, consolidate information and streamline business processes.

That said, like any powerful tool, a Linked Server calls for understanding and good judgment. Don’t use it for everything! Always weigh your project’s needs:

  • For quick ad hoc queries across servers: A Linked Server is perfect.
  • For large-scale data integration or complex ETL processes: Consider tools like SQL Server Integration Services (SSIS), Azure Data Factory, or other data orchestration solutions.
  • For keeping synchronized copies of data: SQL Server Replication or Always On Availability Groups may be a better fit.

I hope this detailed guide has demystified Linked Servers for you. It’s an excellent way to connect data worlds and expand what your SQL Server environment can do.

If you have any questions or suggestions, or want to share your experience with Linked Servers, leave a comment below! I’d love to hear how you’re using this tool in your projects.

See you next time, and happy coding!

Built with Hugo
Theme Stack designed by Jimmy