Accessing Remote Data  «Prev  Next»
Lesson 6Accessing remote data with a linked server
ObjectiveExecute a stored procedure on a remote SQL Server instance and join local and remote tables, using the appropriate linked-server options and permissions.

Execute Remote Procedures and Join Tables with a Linked Server

A linked server can support both remote procedure calls and queries that combine data from different instances. In this SQL Server 2025 lesson, your query window connects to Instance A, and a linked-server definition named RemoteB on A targets Instance B. You will check that definition, distinguish the settings required for each operation, invoke a remote procedure, and join a local sales table to a remote customer table.

The definition belongs on the instance that initiates access. A uses RemoteB to reach B; B does not need a reverse link merely to return results. RemoteB is the configured alias on A and need not equal B's hostname. These instances correspond to ServerA and ServerB in the original scenario. Microsoft's linked-server overview describes this architecture.

Build on the preceding lessons about login mappings and four-part object names. Assume that the link has already been created and its security configuration reviewed. Creating another link is unnecessary when an existing definition targets the required instance.

Identify the example objects and their locations

ComponentExampleLocation or purpose
Connected instanceInstance AReceives the learner's batch
Linked-server definitionRemoteBConfigured on A; targets B
Remote procedureAccounting.dbo.usp_TrimSpaceExecutes on B
Local tableSalesDB.dbo.SalesStored on A
Remote tableAccounting.dbo.CustomersStored on B

These are illustrative application objects, not tables and procedures installed automatically by SQL Server. The Accounting database must exist on B, and the effective remote account must have the permissions needed for the selected operation. Access to another database through this link does not automatically grant access to Accounting.

The local SalesDB in this example is on A. It is distinct from any database with the same name on B. The dbo component identifies a schema, which is a namespace containing database objects. It does not identify the login used for the connection. Schema ownership is a separate relationship, as explained in Microsoft's user-schema separation documentation.

1. Inspect the link on Instance A

Confirm the query window's connection before inspecting the link. A definition on a different instance cannot be selected simply by typing its alias. A caller with appropriate metadata visibility can inspect the existing definition using this query:

-- Connected to Instance A.
SELECT
    name,
    provider,
    data_source,
    is_rpc_out_enabled,
    is_data_access_enabled,
    is_remote_proc_transaction_promotion_enabled
FROM sys.servers
WHERE name = N'RemoteB'
  AND is_linked = 1;

The result describes configuration. It does not prove that B is reachable or that a particular procedure will execute. The destination and provider help identify the connection being examined; the flags describe enabled capabilities. An empty result requires checking both the alias and metadata visibility. Ask the administrator to confirm the definition when the caller cannot see it. See the sys.servers reference for these columns and visibility rules.

For SQL Server 2025, MSOLEDBSQL uses Microsoft OLE DB Driver 19 and requires an explicit encryption choice. The earlier configuration lesson uses Encrypt=Mandatory with an appropriately trusted certificate and matching destination identity. A certificate failure needs a connection-configuration correction; changing a table name or granting more database permissions will not fix it. Consult the SQL Server 2025 provider requirements when reviewing the setup.

2. Enable the capabilities required by the exercise

The rpc out option enables procedure calls from A to the linked destination. The separate data access option enables distributed table queries. The incoming rpc setting is not a replacement for outgoing RPC. An administrator with ALTER ANY LINKED SERVER permission can configure the existing link:

-- Administrator on Instance A; RemoteB already exists.
EXEC master.dbo.sp_serveroption
    @server = N'RemoteB',
    @optname = N'rpc out',
    @optvalue = N'true';

EXEC master.dbo.sp_serveroption
    @server = N'RemoteB',
    @optname = N'data access',
    @optvalue = N'true';

These administrative changes enable capabilities; they do not create remote accounts or grant permissions on application objects. Configure the required capabilities for the workload, then perform the learner's operations under the intended caller's identity. The sp_serveroption reference defines the options and required permission.

3. Test the intended caller's connection

Different callers on A can use different remote identities. A successful administrator connection therefore does not establish that an application login can use the link. Test from a session representing the intended caller:

-- Connected to Instance A as the intended caller.
EXEC master.dbo.sp_testlinkedserver
    @servername = N'RemoteB';

The procedure tests connectivity and raises an exception if the connection fails. It returns no business-data result set. A successful test still leaves object-level authorization to check: the remote account might connect successfully while lacking permission to execute a procedure or read a table. The caller needs an appropriate login mapping, as documented for sp_testlinkedserver.

Keep connectivity, authentication, and authorization separate when investigating failures. A reachable server can reject credentials, and accepted credentials can identify an account without the required object permissions. Making the remote account more privileged should not be the default response to an unexplained error.

4. Invoke the remote stored procedure

This example retains the application procedure name usp_TrimSpace. Its definition and parameter list are not supplied. The following call therefore assumes that the procedure already exists on B and can be invoked without required arguments. Check the actual definition and side effects in the intended test environment first. If parameters are required, supply values that match that definition.

-- Connected to Instance A.
-- Assumes this procedure exists on B and needs no arguments.
EXEC [RemoteB].[Accounting].[dbo].[usp_TrimSpace];

Read the four components as the linked-server name, database, schema, and procedure. A resolves RemoteB and sends the call to B, where the procedure executes in Accounting under the applicable remote security context. Any returned results travel through A to the client. The query window remains connected to A.

The mapped remote identity needs execution permission. A SELECT permission on a table is not permission to execute a procedure. Conversely, procedure access does not necessarily require giving the caller direct access to every underlying table: the requirements depend on the procedure's definition and security context. The EXECUTE reference describes module execution and parameter handling.

The name alone does not establish whether this procedure changes data, returns rows, or trims a particular value. There is no supplied output grid to reproduce. When comparing a remote call with a direct call on B, compare the procedure version, arguments, effective identity, session settings, data, and transaction context. Different conditions can produce different results even when the procedure name matches.

If the installed procedure requires parameters, inspect their names, types, and defaults before adapting the call. Positional arguments must follow the declared order; named arguments identify the intended parameters explicitly. An output parameter also requires the corresponding calling convention. A procedure's integer return status, output parameters, and result sets are different ways of communicating with the caller. Determine which the application expects rather than treating the appearance of any returned value as proof that the intended work succeeded.

5. Establish the join's data assumptions

The second operation combines local sales with remote customer details. Assume the following application schema:

Matching column names or numeric values alone do not establish a valid relationship. If each system assigns its own unrelated customer numbers, an equality join can associate a sale with the wrong customer. Confirm the identifier's meaning before adapting the example to a real application. The linked server transports the request; it does not establish the business relationship between records.

6. Join the local and remote tables

Remain connected to A and request a small, ordered set of sales for customer 42:

-- Connected to Instance A; RemoteB targets Instance B.
DECLARE @CustomerID int = 42;

SELECT TOP (25)
    s.SaleID,
    s.CustomerID,
    s.SaleAmount,
    c.CustomerName
FROM [SalesDB].[dbo].[Sales] AS s
INNER JOIN [RemoteB].[Accounting].[dbo].[Customers] AS c
    ON c.CustomerID = s.CustomerID
WHERE s.CustomerID = @CustomerID
ORDER BY s.SaleID;

The three-part Sales reference resolves within A. The four-part Customers reference uses RemoteB to reach B. The aliases s and c make column references shorter and clearer; they do not change either table's location. The join condition matches customer identifiers, while the WHERE condition selects the requested customer.

INNER JOIN returns matched sales. A sale without a corresponding remote customer is omitted. Because CustomerID is assumed unique in Customers, each matching sale has one matching customer row. If that assumption fails, a sale can appear multiple times. Do not hide unexpected duplication with DISTINCT before examining the relationship. Microsoft's join documentation explains the logical operations.

TOP limits the final result to at most 25 rows, and ORDER BY selects and presents them by the assumed unique SaleID. An empty result can be valid: there might be no sales for customer 42 or no matching customer record. The actual data determines the output. See the TOP reference for ordered row selection.

A report that must retain unmatched local sales needs a different requirement, such as a LEFT JOIN with suitable handling of missing customer details. Changing the join type changes the result's meaning. Decide whether unmatched sales should be omitted, displayed, or investigated before changing the statement.

Read one resulting row as a local sale accompanied by its matching remote customer's name. SaleAmount comes from the Sales table; the statement does not calculate a new total or convert currencies. CustomerName comes from Customers at query time. The query does not copy the customer table permanently, synchronize the two databases, or correct inconsistent customer identifiers. Those would be separate application operations with their own requirements.

Measure the work performed by the join

A limit on returned rows is not a measurement of rows examined or network traffic. SQL Server can delegate supported operations to the OLE DB provider, including filtering, projection, and joins. A four-part reference does not force the entire remote table to be downloaded before processing. The query and provider capabilities influence the chosen plan.

Inspect the plan's remote operations and compare equivalent requests on stable data. Relevant indexes, available statistics, data distribution, and connection latency can affect performance. The query-processing architecture guide describes how SQL Server distributes work across OLE DB sources.

Validate the result before tuning it. Check selected columns, key relationships, filtering, and ordering first. If the real tables use different data types or incompatible text collations, investigate that mismatch. This example joins integer keys, so adding a blanket collation change would not address its stated requirements.

A useful test dataset includes a customer with several sales, a customer with no sales, and a sale whose customer is absent remotely. Check which rows the chosen join should retain in each case. Compare the returned identifiers with those expectations before comparing elapsed time. When data changes between executions, different row counts do not by themselves demonstrate that a query change improved or broke the report.

7. Review the transaction context

The practice statements do not explicitly start a transaction. That does not establish what the unknown application procedure does internally or what transaction context an application may already have established. Review the session and procedure behavior before treating several operations as one unit of work.

For linked-server calls, remote proc transaction promotion defaults to true. A call from an active local transaction can enlist remote work through Microsoft Distributed Transaction Coordinator, or MS DTC. With no transaction active before the call, this option has no effect. Disabling it does not remove an already distributed transaction. Review its conditions in the sp_serveroption documentation linked above.

BEGIN DISTRIBUTED TRANSACTION explicitly starts a coordinated transaction. It is not required merely because an object is remote. Distributed queries within local transactions can also cause promotion when the provider supports the required transaction interface. Consequently, explicit distributed-transaction syntax is not the only route to enlistment. The distributed transaction reference explains these conditions.

Starting the Windows DTC service alone does not demonstrate that two machines can coordinate transactions. Communication, firewall rules, and the environment's security configuration must permit the participating systems to work together. Administrators can consult Microsoft's DTC firewall guidance. Disabling transaction promotion merely to suppress an error can change the application's transaction behavior.

The older SET REMOTE_PROC_TRANSACTIONS compatibility option is not the control for this linked-server scenario. It concerns older remote-server definitions, as its documentation clarifies. For later designs that modify data through OLE DB inside transactions, also review SET XACT_ABORT and error handling. Those concerns do not configure DTC automatically.

Keep provider capabilities in view

This lesson targets another SQL Server instance. Linked servers can expose other data sources through suitable OLE DB providers, including ODBC sources reached through an appropriate bridge. That does not guarantee that every source supports the same query syntax, procedure calls, or transaction behavior. Verify the specific provider's supported operations before transferring this walkthrough to another database product.

OPENQUERY and OPENROWSET provide additional access forms covered elsewhere in this module. They do not remove the need to understand credentials, object permissions, or provider capabilities. Choose an access form for its actual requirements rather than assuming that changing the function name fixes a connection or security problem.

Diagnose the operation that failed

Separate failures by the stage reached. These checks narrow an investigation; they do not establish a single cause for every error:

Record the exact statement, originating instance, caller context, and relevant error when seeking help. Keep passwords and connection-string secrets out of shared reports. A successful test at one stage is useful evidence, but it does not replace testing the operation the application actually needs.

After a correction, repeat the failing operation under the same intended caller and confirm its result. Changing several unrelated settings at once makes the cause harder to identify. Keep administrative configuration work separate from the application's normal query sequence so routine execution does not depend on repeatedly modifying the linked server.

Practice accessing remote data

Before attempting the exercise, identify where the link is defined, which option enables outgoing calls, and which identities need permission on the local and remote objects. Then explain why the join uses three parts for Sales and four for Customers. Finally, decide whether the intended operation runs within an existing transaction.

Continue with the Accessing Remote Data - Exercise. In the next lesson, you will examine OPENROWSET; a later lesson develops OPENQUERY further.


SEMrush Software 6 SEMrush Banner 6