Knowledge · Distributed queries

Linked server slow? Where the time really goes

“My query over the linked server returns ten rows and still takes seconds.” That is how many questions about linked servers start. The four-part name LS_Remote.LinkedLab.dbo.Orders looks like a local table. Behind it, though, is a conversation between two servers.

Updated Nov 27, 2026 · approx. 20 min read

Lab SQL Server 2022 · 2025SQL query 1Topic Remote Query · OPENQUERY · EXEC AT
Share
Your serverruns the queryRemote serverholds the dataOptimizerremote call →← rows

The cost depends on three things: how much data crosses the wire, how often the local server asks the remote server, and what the local plan can no longer do as a result. This page uses a lab with two SQL Server instances to show how to tell from the plan which of the three is hurting you, and what to write instead. We tested on SQL Server 2025 CU10 and cross-checked on 2022 CU27. The diagnostic query at the end runs on SQL Server 2019 and later.

In short

  • The local server decides for each expression whether the filter goes along. = 'TARGET', LIKE 'TARG%', IN and UPPER() went to the remote server as a WHERE clause. YEAR(), FORMAT() and a scalar function that could not be inlined fetched 1 million rows for 10 matches. A differing COLLATE also fetched all rows and returned 20 matches instead of 10.
  • Joins with local tables query once per key, in the lab still at 30,000 keys. 10,000 local keys meant 10,000 remote queries. Each cost about 0.8 ms directly and about 3.6 ms with 2 ms of added latency. At 30,000 keys and 2 ms of added latency, that was 108 s against 1.8 s for the whole table.
  • Writes often go row by row, through OPENQUERY as well. 1,000 rows written with a four-part INSERT arrived as 1,000 separate sp_cursor calls. With EXEC … AT and a JSON set, it was one statement.
  • A four-part query costs six remote calls on every execution, and 13 to 15 on its first compilation. EXEC … AT needed two. Loops, cursors and triggers pay that on every pass.
  • The local plan loses capabilities. In the lab it never ran in parallel, TOP did not go along, and OPENQUERY and EXEC … AT always estimated 10,000 rows.
SELECT OrderID FROM LS_Remote.LinkedLab.dbo.Orders WHERE OrderID = 7;

On the first compile 13 to 15 calls, among them

  1. sp_tables_info_90_rowset_64
  2. sp_columns_100_rowset
  3. sp_indexes_100_rowset
  4. sp_check_constbytable_rowset
  5. sp_table_statistics2_rowset
  6. DBCC SHOW_STATISTICS … HISTOGRAM_STEPS
  7. SELECT @@SPID
  8. collationname()
  9. sp_getschemalock
  10. sp_releaseschemalock
  11. sp_reset_connection

On every run 6 calls

  1. SET XACT_ABORT OFF
  2. sp_getschemalock
  3. sp_prepexecreturns the row
  4. sp_unprepare
  5. sp_releaseschemalock
  6. sp_reset_connection
remote calls of this run6every further run
  • First run13 to 15 calls (compile)
  • Every further run6 calls
  • EXEC … AT2 calls per run

A packet is one remote call, i.e. one sql_batch_completed or rpc_completed event of the linked server login on the remote server, not a network packet. Applies to the four-part query; EXEC … AT needs 2 calls per run. SQL Server 2025 CU10, cross-check on 2022 CU27, three runs with the same counts. Timing schematic.

One row, six remote calls: what crosses the wire behind a four-part name.

The lab

Two SQL Server instances: the local server runs the queries. The remote server holds the table Orders with 1 million rows, exactly ten of them with CustomerCode = 'TARGET'. The linked server is called LS_Remote and uses the provider MSOLEDBSQL. It signs in on the remote server with a SQL login that only has object permissions. For every query we measured:

  • the text the local server sends to the remote server (the remote text from here on)
  • the rows and the amount of data on the wire
  • every single call on the remote server, with Extended Events (a remote call from here on)
  • the duration at the client

Selected cases also ran with artificially added latency: 2 ms and 10 ms more per round trip (RTT). This shows what a slower connection does to the same pattern. The duration at the client includes about 0.25 s for starting the tool. Times below one second are therefore rough values only. You can rebuild the setup with three scripts; they are under Rebuild the lab. How we measured is under What the test shows.

Where is the filter applied? Read the remote text

Many developers believe the remote server never filters and always sends the whole table. Others believe the opposite. Neither is right. The local optimizer checks each expression in the WHERE clause on its own. If it can safely phrase the expression as SQL text, it sends it along. If it can't, it fetches the rows and evaluates the expression itself.

What it sends is in the actual execution plan. With a four-part name, the operator is called Remote Query, and its property Remote Query holds the remote text. With OPENQUERY, the operator is called Remote Scan, and the text is in RemoteObject. With EXEC … AT, that property only says STREAM. You can then see the executed text only on the remote server, for example with Extended Events. What counts is the remote text, not your query.

Ten matches, but what crosses the wire?

Equality on a character column
SELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE CustomerCode = 'TARGET';   -- goes to the remote server as WHERE

Remote text with WHERE on CustomerCode · 10 rows · 1 KB · 0.26 s

Function on the remote column
SELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE YEAR(CreatedAt) = 2099;   -- fetches the whole table, filters locally

Remote text without WHERE · 1,000,000 rows · 11.8 MB · 2.1 s

The same condition as a range
SELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE CreatedAt >= '20990101' AND CreatedAt < '21000101';   -- range instead of function

Remote text with WHERE on CreatedAt, both bounds · 10 rows · 1 KB

Own function, not inlineable
-- dbo.fnNormNoInline from the setup script: RETURN UPPER(@s), WITH INLINE = OFFSELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE dbo.fnNormNoInline(CustomerCode) = 'TARGET';   -- runs locally, row by row

Remote text without WHERE · 1,000,000 rows · 12.7 MB · 5.6 s

SQL Server 2025 CU10, 1 million rows on the remote server, median of three runs. The remote text is in the actual execution plan on the Remote Query operator.

In the lab, two groups of expressions led to the whole table: built-in functions such as YEAR() and FORMAT(), and scalar functions without inlining. An inlineable function that only calls UPPER(), on the other hand, went along as upper(…). Only 10 rows and 1 KB crossed the wire. To get them, though, the remote server had to read its whole index (2,496 instead of 3 reads), because it can't seek after UPPER(). A function on the column costs you even when the filter goes along.

WHERE YEAR(CreatedAt) = 2099
Rows over the wire1,000,000
Rows in the result10
  • Filterlocally on your server
Data volume11,8 MB
Remote text in the plan
SELECT "Tbl1002"."OrderID" "Col1004","Tbl1002"."CreatedAt" "Col1007" FROM "LinkedLab"."dbo"."Orders" "Tbl1002"no WHERE

Optimizer: I can't translate YEAR() safely. I fetch the rows and evaluate it myself.

All eight predicates at a glance
PredicateFilterRows over the wireDataResult
WHERE CustomerCode = 'TARGET'remote101 KB10
WHERE YEAR(CreatedAt) = 2099local1,000,00011,8 MB10
WHERE CreatedAt >= '20990101' AND CreatedAt < '21000101'remote101 KB10
WHERE dbo.fnNormNoInline(CustomerCode) = 'TARGET'local1,000,00012,7 MB10
WHERE CodeCS = 'TARGET' COLLATE Latin1_General_100_CI_ASlocal1,000,00014,3 MB20
WHERE YEAR(CreatedAt) = 2099 AND CustomerCode = 'TARGET'split101 KB10
WHERE OrderID = 7 OR CustomerCode = 'TARGET'remote101 KB10
WHERE YEAR(CreatedAt) = 2099 OR CustomerCode = 'TARGET'local1,000,00020,5 MB10

Four-part name, 1 million rows and 10 matches on the remote server. Data volume at the local network adapter, median of three runs on SQL Server 2025 CU10; date range and COLLATE from the follow-up runs (Nov 28/29, 2026).

Where the filter sits decides what crosses the wire.

Two inconspicuous triggers: COLLATE and OR

A COLLATE in a comparison looks harmless. If the collation you specify differs from the collation of the remote column, the local server fetches the whole table and compares the rows itself. The result can change in the process. If the COLLATE matches the remote column, the filter goes along. The same applies to COLLATE DATABASE_DEFAULT when the local database has the same collation.

With AND, the optimizer passes on the simple parts and keeps the rest. An OR of two simple comparisons went along as well, for example OrderID = 7 OR CustomerCode = 'TARGET'. But if one part of the OR is something the optimizer can't translate, no filter goes along at all.

COLLATE and OR: two inconspicuous triggers

CI comparison on a CS column
SELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE CodeCS = 'TARGET' COLLATE Latin1_General_100_CI_AS;   -- differs from the remote column

Remote text without WHERE · 20 instead of 10 rows · 14.3 MB

Same collation as the remote column
SELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE CodeCS = 'TARGET' COLLATE Latin1_General_100_CS_AS;   -- as on the remote server

Remote text with WHERE · 10 rows · 1 KB

Function next to a simple filter
SELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE YEAR(CreatedAt) = 2099  AND CustomerCode = 'TARGET';   -- this part goes along

Remote text with WHERE on CustomerCode only · 10 rows · YEAR() applied locally to 10 rows

The same conditions combined with OR
SELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE YEAR(CreatedAt) = 2099   OR CustomerCode = 'TARGET';   -- untranslatable part in the OR: no filter

Remote text without WHERE · 1,000,000 rows · 20.5 MB

On the remote server CodeCS is Latin1_General_100_CS_AS (ten times TARGET, ten times target), CustomerCode is Latin1_General_100_CI_AS. SQL Server 2025 CU10.

OPENQUERY: the filter belongs in the text

OPENQUERY sends exactly the text you specify. The local server evaluates a WHERE clause outside of it only after the transfer.

OPENQUERY: filtered inside or outside

WHERE in the OPENQUERY text
SELECT OrderIDFROM OPENQUERY(LS_Remote,     'SELECT OrderID FROM LinkedLab.dbo.Orders WHERE CustomerCode = ''TARGET''');   -- filter in the text

10 rows · 1 KB · 0.27 s

WHERE outside OPENQUERY
SELECT OrderIDFROM OPENQUERY(LS_Remote, 'SELECT OrderID, CustomerCode FROM LinkedLab.dbo.Orders')WHERE CustomerCode = 'TARGET';   -- the local server filters only after the transfer

1,000,000 rows · 12.7 MB · 1.6 s (3.5 s at +2 ms RTT)

SQL Server 2025 CU10, median of three runs.

When the join queries once per key

In code, a join between a local table and a remote table looks like any other join. In the lab, the optimizer almost always chose nested loops. The local server then sends a parameterized query (WHERE ?="OrderID") to the remote server for every local key. Each one is fast. The sum is expensive, because every query has to make a round trip.

The optimizer estimates one row for each of these queries. It doesn't know the latency of the connection. That is why it sticks with this plan for a long time: at 30,000 local keys it still chose one query per key, also with added latency. At 100,000 keys it chose a merge join with the whole table. We did not search for the exact switching point in between. On 2022 it behaved the same way.

Remote calls30,00030,000 remote queries, one per key
Measured108 smedian, client time

Optimizer: estimates 1 row per access and does not know the latency of the line.

All measurements
FormKeysdirect+2 ms RTT+10 ms RTT
Optimizer1000.37 s0.73 s1.72 s
Optimizer3,0002.63 s11.2 s36.5 s
Optimizer30,00023.4 s108 snot measured
HASH JOIN1001.24 s1.80 s4.50 s
HASH JOIN3,0001.22 s1.81 s4.48 s
HASH JOIN30,0001.27 s1.84 snot measured
JSON via EXEC … AT100not measurednot measurednot measured
JSON via EXEC … AT3,0000.29 s0.32 s0.38 s
JSON via EXEC … AT30,0000.53 s0.78 snot measured

Join of a local key table with Orders, keys spread evenly over 1 to 1,000,000, one result row. Median of three runs on SQL Server 2025 CU10, client time including about 0.25 s of measuring overhead. Latency added artificially (+1 ms or +5 ms each way). Motion schematic: the first few round trips in sequence, then fast-forward.

One round trip per row: how often the local server asks the remote server.

30,000 local keys, three ways

Join without a join hint
SELECT COUNT_BIG(*), SUM(CAST(r.OrderID AS bigint))FROM dbo.FilterIDs30000 AS lJOIN LS_Remote.LinkedLab.dbo.Orders AS r ON r.OrderID = l.ItemID;   -- one query per key

Nested loops · 30,000 remote calls · 23.4 s / 108 s

Whole table in one stream
SELECT COUNT_BIG(*), SUM(CAST(r.OrderID AS bigint))FROM dbo.FilterIDs30000 AS lINNER HASH JOIN LS_Remote.LinkedLab.dbo.Orders AS r ON r.OrderID = l.ItemID;   -- join hint

1 remote query · 1,000,000 rows · 1.27 s / 1.84 s

Keys as a set to the remote server
DECLARE @j nvarchar(max) = (SELECT ItemID FROM dbo.FilterIDs30000 FOR JSON PATH);EXEC (N'SELECT COUNT_BIG(*), SUM(CAST(o.OrderID AS bigint))        FROM LinkedLab.dbo.Orders AS o        JOIN OPENJSON(?) WITH (ID int ''$.ItemID'') AS j ON j.ID = o.OrderID',      @j) AT LS_Remote;   -- one statement, one plan

1 statement on the remote server · 1 result row back · 0.53 s / 0.78 s

Keys spread evenly over 1 to 1,000,000, result as one row. Times direct / +2 ms RTT, median of three runs on SQL Server 2025 CU10. The latency is artificial.

The cost per key shows how much latency matters: about 0.8 ms direct, 3.6 ms with 2 ms of added latency and 12 ms with 10 ms. By contrast, the whole table with HASH JOIN cost almost the same at each latency level, about 1.2 to 1.3 s, 1.8 s and 4.5 s, regardless of the number of keys. With 10 ms of added latency, we measured that only up to 3,000 keys.

Local keysOptimizer's plandirect+2 ms RTT+10 ms RTT
100one query per key0.37 s0.73 s1.72 s
3,000one query per key2.63 s11.2 s36.5 s
30,000one query per key23.4 s108 snot measured
100,000merge join, whole table1.27 snot measurednot measured
30,000 with HASH JOINwhole table1.27 s1.84 snot measured

By calculation, the whole table would have been cheaper here from about 1,200 keys on, from about 400 with 2 ms of added latency and from about 330 with 10 ms. We calculated these limits linearly from the measured points; we did not measure them individually. They depend on the size of the remote table: the larger it is, the more expensive the whole table becomes, and the later it pays off. The REMOTE join hint did not change the plan.

direct+2 ms RTT+10 ms RTTone query per keywhole table (HASH JOIN)optimizer after switching (merge join)computed, not measured
0.20.51251020501001003001,0003,00010,00030,000100,000300,000local keys (logarithmic)secondsswitchesbetween 30,000 and 100,000costly range: asks per keycomputed ≈ 1,200computed ≈ 400computed ≈ 330

Measured points: median of three runs on SQL Server 2025 CU10, one result row, client time including about 0.25 s of overhead; +10 ms RTT at 30,000 keys and 100,000 keys with latency not measured. The optimizer still chose one query per key at 30,000 and a merge join at 100,000; nothing in between was measured. The crossing points are computed linearly from the measured points and depend on the table size (1 million rows here). Same plan shape on 2022 CU27.

The threshold: the optimizer sticks with one query per key for a long time.

Six remote calls for one row

Even a single query is more than one remote call. On its first compilation, the local server sends 13 to 15 calls to the remote server. Six of them fetch metadata and statistics, among them sp_columns_100_rowset, sp_indexes_100_rowset and DBCC SHOW_STATISTICS. Every further execution of the same four-part query cost six calls, even with the plan in cache: SET XACT_ABORT OFF, sp_getschemalock, sp_prepexec, sp_unprepare, sp_releaseschemalock and sp_reset_connection.

That doesn't matter as long as a query runs once. In a loop, a cursor, a trigger or a scalar function, you pay it on every pass. With literals in the text, compilation comes on top, and the remote server creates a separate plan for every value.

100 queries for one row each

Dynamic SQL with the value in the text
DECLARE @i int = 1, @s nvarchar(400);WHILE @i <= 100BEGIN    SET @s = CONCAT(N'DECLARE @x int; SELECT @x = OrderID FROM LS_Remote.LinkedLab.dbo.Orders WHERE OrderID = ',                    @i * 7, N';');   -- every value a new text    EXEC (@s);    SET @i += 1;END;

1,500 remote calls · 102 plans on the remote server · 4.0 s / 25.3 s

sp_executesql, four-part
DECLARE @i int = 1, @x int;WHILE @i <= 100BEGIN    EXEC sys.sp_executesql N'SELECT @x = OrderID FROM LS_Remote.LinkedLab.dbo.Orders WHERE OrderID = @id',         N'@id int, @x int OUTPUT', @id = @i, @x = @x OUTPUT;   -- one plan, six calls per execution    SET @i += 1;END;

609 remote calls · 1 plan · 1.10 s / 10.3 s

Text with a parameter straight to the remote server
DECLARE @i int = 1;WHILE @i <= 100BEGIN    EXEC (N'DECLARE @x int; SELECT @x = OrderID FROM LinkedLab.dbo.Orders WHERE OrderID = ?', @i)         AT LS_Remote;   -- two calls per execution    SET @i += 1;END;

200 remote calls · 1 plan · 0.73 s / 2.97 s

Remote calls counted with Extended Events, plans counted in the plan cache of the remote server. Times direct / +10 ms RTT, median of three runs on SQL Server 2025 CU10. The literal loop ran with an empty plan cache and reads IDs 7 to 700, the other two IDs 1 to 100.

EXEC … AT needs two remote calls per execution (sp_executesql and sp_reset_connection), because the local server doesn't plan the text itself. The option lazy schema validation made no difference to the metadata calls.

Literal, four-part

102 plans in the remote plan cache after 100 queries

1,500 remote calls

4.00 s direct · 25.3 s at +10 ms RTT

Parameter, four-part

1 plan in the remote plan cache after 100 queries

609 remote calls

1.10 s direct · 10.3 s at +10 ms RTT

OPENQUERY, dynamic

102 plans in the remote plan cache after 100 queries

600 remote calls

1.24 s direct · 10.3 s at +10 ms RTT

EXEC … AT with parameter

1 plan in the remote plan cache after 100 queries

200 remote calls

0.73 s direct · 2.97 s at +10 ms RTT

100 queries for one row each in a loop. Remote calls counted with Extended Events, plans in the plan cache of the remote server. Times: median of three runs on SQL Server 2025 CU10, client time; latency added artificially.

100 queries, four ways: literals fill the plan cache of the remote server.

Writing through the linked server

When reading, the filter decides; when writing, the form of the statement decides. A simple UPDATE or DELETE on the remote table alone went to the remote server as one statement in the lab. In the tested forms with a local table as the source, the local server wrote row by row: with INSERT … SELECT and with UPDATE with a join. OPENQUERY as the write target didn't help.

Reset both target tables on the remote server before each example:

-- on the remote server, in LinkedLabTRUNCATE TABLE dbo.InsertTarget;TRUNCATE TABLE dbo.WriteTarget;INSERT dbo.WriteTarget (ID, Code, Amount, Note)SELECT OrderID, CustomerCode, Amount, Note FROM dbo.Orders WHERE OrderID <= 100000;
remote calls on the remote server1,000sp_cursoropen and 1,000 × sp_cursor
  • direct1.21 s
  • +2 ms RTT3.92 s
  • +10 ms RTT12.5 s

1,000 rows, counted with Extended Events on the remote server. Times direct / +2 ms / +10 ms RTT, median of three runs on SQL Server 2025 CU10; UPDATE with join measured directly only. Motion schematic, fast-forward.

Writing 1,000 rows: row by row or one statement.

Writing 1,000 rows

INSERT … SELECT from a local table
INSERT INTO LS_Remote.LinkedLab.dbo.InsertTarget (ID, Code, Amount, Note)SELECT ItemID, 'NEW', 1.00, REPLICATE('n', 80)FROM dbo.FilterIDs1000;   -- transferred row by row

sp_cursoropen and 1,000 × sp_cursor · 1.21 s / 12.5 s

The same rows as JSON via EXEC … AT
DECLARE @j nvarchar(max) = (SELECT ItemID AS ID FROM dbo.FilterIDs1000 FOR JSON PATH);EXEC (N'INSERT LinkedLab.dbo.InsertTarget (ID, Code, Amount, Note)        SELECT ID, ''NEW'', 1.00, REPLICATE(''n'', 80) FROM OPENJSON(?) WITH (ID int)',      @j) AT LS_Remote;   -- one statement on the remote server

one statement · 0.27 s / 0.30 s

UPDATE of the remote table with a local join
UPDATE r SET Amount = r.Amount + 1FROM LS_Remote.LinkedLab.dbo.WriteTarget AS rJOIN dbo.FilterIDs1000 AS l ON l.ItemID = r.ID;   -- one statement per row

1 × sp_prepexec, 999 × sp_execute · 1.13 s direct, not measured with latency

OPENQUERY as the write target
UPDATE OPENQUERY(LS_Remote, 'SELECT ID, Amount FROM LinkedLab.dbo.WriteTarget WHERE ID <= 1000')SET Amount = Amount + 1;   -- row by row here too

sp_cursorfetch and 1,000 × sp_cursor · 1.86 s / 24.7 s

Text with a parameter
EXEC (N'UPDATE LinkedLab.dbo.WriteTarget SET Amount = Amount + 1 WHERE ID <= ?', 1000)     AT LS_Remote;   -- one statement

one statement · 0.31 s / 0.29 s

What arrives on the remote server, counted with Extended Events. Times direct / +10 ms RTT, median of three runs on SQL Server 2025 CU10. The UPDATE with a join hits IDs 7 to 7,000 in steps of seven, the other variants IDs 1 to 1,000. With JSON, only the IDs cross the wire; the remote server sets the other values.

SQL Server rejects a MERGE with a remote table as its target:

MERGE LS_Remote.LinkedLab.dbo.WriteTarget AS tUSING dbo.FilterIDs10 AS s ON t.ID = s.ItemIDWHEN MATCHED THEN UPDATE SET Amount = 0;-- Msg 5315, Level 16, State 1-- The target of a MERGE statement cannot be a remote table, a remote view, or a view over remote tables.

What the local plan can no longer do

Parallelism. No local plan with a remote operator ran in parallel in the lab. The plan gives NoParallelWithRemoteQuery or CouldNotGenerateValidParallelPlan as the reason. That also affects the local part, for example a hash join over 1 million remote rows. The remote server, on the other hand, may run the remote text in parallel: an expensive grouping ran there with DOP 2, in all three call forms, while the local plan stayed serial. If the local part is large, load the remote rows into a temporary table first. INSERT #t SELECT … FROM LS_Remote… fetched 1,000 rows with one remote call.

TOP. TOP (10) … ORDER BY, OFFSET … FETCH and ROW_NUMBER() … <= 10 went to the remote server without TOP, only with ORDER BY. The local server stops the data stream after ten rows. With a matching index that is cheap. Without a matching index, the remote server sorts the whole table, for ten rows.

TOP (10): what the remote server has to do for it

ORDER BY on the primary key
SELECT TOP (10) OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersORDER BY OrderID DESC;   -- the index provides the order

71 to 72 reads on the remote server

ORDER BY without a matching index
SELECT TOP (10) OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersORDER BY CustomerCode DESC, OrderID;   -- remote server sorts everything

2,502 reads · whole table sorted for 10 rows · 0.97 s

Reads on the remote server with Extended Events, plan in cache, the same in all three repetitions. SQL Server 2025 CU10.

Aggregates, on the other hand, go along: COUNT_BIG(*), GROUP BY and a TOP over a grouping came back as one to five rows.

Estimates. With a four-part name, the local server fetches the histogram from the remote server for many filters. For an equality on an indexed column, it estimated exactly 10 rows that way. For a range on the primary key (OrderID BETWEEN 1 AND 10) it fetched no histogram and estimated 90,000 instead of 10. In the tested plans, OPENQUERY and EXEC … AT always estimated 10,000 rows, whether 1 or 1 million came back. When the remote table had a row-level security policy, the local server no longer fetched a histogram through our login with object permissions and used a fixed estimate.

TOP (10) does not go along

  • Remote textORDER BY … TOP
  • Reads remote71–72
  • Remote serverreads in index order, A stops after 10 rows

Parallel only on the remote server

Expensive grouping over 1 million rows: your server planned serially (NoParallelWithRemoteQuery), the remote server ran it with DOP 2 (last_dop = 2), in all three call forms.

Reads on the remote server via Extended Events, SQL Server 2025 CU10, repeated runs with the plan cached. Parallelism from sys.dm_exec_query_stats.last_dop on the remote server (follow-up run Nov 28, 2026, same on 2025 and 2022).

What the local plan can no longer do: pass on TOP and run in parallel.

Transactions: two stumbling blocks

INSERT … EXEC … AT turns the query into a distributed transaction without you asking for it. That is the default (remote proc transaction promotion = true). In the lab, 10 rows took 2.98 s that way, and 0.46 s with the option turned off. On SQL Server 2019 in a Linux container, the same statement failed with Msg 7391 because no distributed transaction was possible.

INSERT … EXEC … AT and the distributed transaction

remote proc transaction promotion = true
DROP TABLE IF EXISTS #t;CREATE TABLE #t (OrderID int);INSERT #t   -- INSERT … EXEC promotes to a distributed transactionEXEC (N'SELECT OrderID FROM LinkedLab.dbo.Orders WHERE OrderID <= 10') AT LS_Remote;

distributed transaction · waits PREEMPTIVE_OS_DTCOPS and DTC · 2.98 s

remote proc transaction promotion = false
EXEC sys.sp_serveroption N'LS_Remote', N'remote proc transaction promotion', N'false';   -- applies to the whole linked serverGODROP TABLE IF EXISTS #t;CREATE TABLE #t (OrderID int);INSERT #tEXEC (N'SELECT OrderID FROM LinkedLab.dbo.Orders WHERE OrderID <= 10') AT LS_Remote;GOEXEC sys.sp_serveroption N'LS_Remote', N'remote proc transaction promotion', N'true';    -- back to the default

no distributed transaction · 0.46 s

10 rows, SQL Server 2025 CU10, median of three runs (range of the first variant 2.98 to 3.99 s).

The option applies to all queries through this linked server. Turn it off only if none of these queries needs a distributed transaction. Otherwise, changes on both sides are no longer protected together.

The second stumbling block is XACT_ABORT. A four-part UPDATE in an explicit transaction fails as long as XACT_ABORT is off, and that is the default in many sessions:

SET XACT_ABORT OFF;BEGIN TRAN;UPDATE LS_Remote.LinkedLab.dbo.WriteTarget SET Amount = 0 WHERE ID = 1;IF @@TRANCOUNT > 0 COMMIT;-- Msg 7395, Level 16, State 2-- Unable to start a nested transaction for OLE DB provider "MSOLEDBSQL19" for linked server "LS_Remote".-- A nested transaction was required because the XACT_ABORT option was set to OFF.

With SET XACT_ABORT ON; before BEGIN TRAN, the same transaction ran through.

Same SQL, different result

On the remote server, the column CodeCS is case-sensitive. It holds TARGET ten times and target ten times. The local database is case-insensitive. The same query then returns 10 or 20 rows, depending on the server option use remote collation.

WHERE CodeCS = 'TARGET'

B · CS · 10 rows

  • Compared byCS collation of the remote side
  • Result10 rows (TARGET only)
  • Over the line10 rows · 1 KB

Column CodeCS on the remote server is Latin1_General_100_CS_AS with ten TARGET and ten target, the local database is Latin1_General_100_CI_AS. collation compatible had no measurable effect. SQL Server 2025 CU10, median of three runs.

Same SQL, different result: a server option moves the filter.

The same query, 10 or 20 rows

use remote collation = true
SELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE CodeCS = 'TARGET';   -- compared using the remote collation

filter goes along · 10 rows (TARGET only) · 1 KB

use remote collation = false
EXEC sys.sp_serveroption N'LS_Remote', N'use remote collation', N'false';   -- local collation appliesGOSELECT OrderIDFROM LS_Remote.LinkedLab.dbo.OrdersWHERE CodeCS = 'TARGET';GOEXEC sys.sp_serveroption N'LS_Remote', N'use remote collation', N'true';    -- back to the default

no filter · 20 rows (TARGET and target) · 13.6 MB · 1.64 s

SQL Server 2025 CU10.

With the default setting, the remote server compares using the collation of its column, that is case-sensitively. With false, the local server fetches the rows and compares using the collation of its instance, here case-insensitively. A developer who queries a local copy with a case-insensitive column also gets 20 rows. The option collation compatible had no measurable effect in the four combinations we tested, not even on where the filter ran. According to Microsoft, it requires the same character sets and sort orders. Turn it on only if that is certain for both servers. A differing COLLATE in the query causes the same shift (see above).

Is OPENQUERY the solution?

OPENQUERY has two advantages. The filter is guaranteed to be in the text, and the metadata calls during compilation go away. It doesn't solve the other problems:

  • Variable values require dynamic SQL. The remote server then creates one plan per value, 102 plans for 100 values. That was not faster than a four-part query with a parameter: 1.24 s against 1.10 s direct, both 10.3 s with 10 ms of added latency.
  • Key lists hit a limit. According to Microsoft, the text can be at most 8 KB long.
  • The fixed estimate of 10,000 rows disturbs local joins. An OPENQUERY without a filter, joined with 3,000 local keys, ran into a spill to tempdb.
  • Writes through OPENQUERY go row by row, as shown above.

Limits of OPENQUERY

3,000 keys in the OPENQUERY text
DECLARE @l nvarchar(max) = (SELECT STRING_AGG(CAST(ItemID AS nvarchar(max)), N',') FROM dbo.FilterIDs3000);DECLARE @s nvarchar(max) = N'SELECT COUNT_BIG(*), SUM(CAST(OrderID AS bigint)) FROM OPENQUERY(LS_Remote,    ''SELECT OrderID FROM LinkedLab.dbo.Orders WHERE OrderID IN (' + @l + N')'')';   -- the list gets too longEXEC (@s);-- Msg 103, Level 15, State 1 (shortened)-- The character string that starts with 'SELECT OrderID FROM LinkedLab.dbo.Orders WHERE OrderID IN (333,666,…'-- is too long. Maximum length is 8000.

Msg 103 · the text is limited to 8 KB

OPENQUERY without a filter, joined locally
SELECT COUNT_BIG(*), SUM(CAST(r.OrderID AS bigint))FROM dbo.FilterIDs3000 AS lJOIN OPENQUERY(LS_Remote, 'SELECT OrderID FROM LinkedLab.dbo.Orders') AS r   -- estimated 10,000, actually 1 million    ON r.OrderID = l.ItemID;

fixed estimate of 10,000 · hash join with spill to tempdb · 3.9 s (four-part with HASH JOIN 1.2 s)

SQL Server 2025 CU10, median of three runs.

In the lab, EXEC … AT with a parameter or a JSON set depended least on latency. It needs two remote calls and one plan on the remote server: 100 queries took 0.73 s direct and 2.97 s with 10 ms of added latency, compared with 10.3 s for a four-part query with a parameter.

Which form when?

  • Four-part name: for simple filters, few rows and queries that don't run in a loop. Check the remote text in the plan.
  • OPENQUERY with the filter in the text: for fixed queries whose result is small and isn't joined locally.
  • EXEC … AT with a parameter or JSON: for variable values, many local keys and every write that uses local data.
  • Provide the data differently, for example as a copy through ETL or replication: when the same remote data is needed all the time. We did not measure this option.

How to proceed

  1. Open the actual execution plan of the slow query.
  2. Open the properties of the Remote Query and Remote Scan operators.
  3. Read the remote text. With EXEC … AT it only says STREAM.
  4. Compare the actual rows on the remote operator with the rows in the result. If the operator returns many more rows and a Filter sits above it, the local server is filtering.
  5. Check the actual number of executions on the remote operator. If it matches the number of local rows, the plan queries once per key.
  6. If the local server is filtering, rewrite the expression as a simple comparison on the column, for example as a date range instead of YEAR().
  7. If the plan queries once per key, send the keys as JSON via EXEC … AT. Alternatively, fetch the whole table with HASH JOIN.
  8. Write through the linked server with EXEC … AT and a parameter or JSON.
  9. After every change, first compare the result with the old result. Then compare the transferred rows and the executions in the plan.
  10. If no INSERT … EXEC … AT through this linked server needs a distributed transaction, set remote proc transaction promotion to false.
  11. Run the diagnostic query below to find such access in your own system.

Find linked server access in your own system

The diagnostic query lists up to 100 remote operators from the plan cache, ordered by the executions of their statement. It shows the remote text, the estimated executions of the operator and a note on the patterns from this page: query per key, local filter, probably the whole table, suspected row-by-row writes and the fixed estimate of 10,000. A second part searches the procedures, functions, views and triggers of the current database for the linked server names. That is how you find stored EXEC … AT, which is missing from the plan cache. You can see ad hoc EXEC … AT only on the remote server, for example with Extended Events.

Query 1: Linked server access in the plan cache · read-only · tested on SQL Server 2019–2025
/* PSG · Linked servers · Query 1: Linked server access in the plan cache   As of Nov 27, 2026 · tested on SQL Server 2019 CU32, 2022 CU27, 2025 CU10 (Linux containers, lab)    WARNING: Run it on a test system or outside peak load first. Part 2 reads the plan text of every statement in the   plan cache of the instance (early filter: @database) and shreds the plans with a remote operator with XQuery; on a   large or busy server this uses noticeable CPU and memory. Review the output before you share it: statement and   remote text from the plan cache may contain confidential values. Run it in a new query window: the DROP TABLE IF   EXISTS statements at the start drop temporary tables of the same names (#psg_plans, #psg_findings) in your   session. Run it at your own risk. The query is read-only (sys.servers, plan cache DMVs, sys.sql_modules), changes   no data, objects or settings, only sets session options (NOCOUNT, QUOTED_IDENTIFIER), drops its two temporary   tables at the end and does not connect to the linked server.    - Part 1, linked servers: options from sys.servers that change where filters run (collation compatible, use     remote collation, collation name). sysadmin sees all linked servers. A login without sysadmin and without its     own linked server mapping saw none in the lab: parts 1 and 3 then stay empty, and a note follows at the end.   - Part 2, plan cache: every statement with a remote operator (Remote Query, Remote Scan, Remote Insert, Remote     Update, Remote Delete), with remote text, estimate and notes. @top_rows limits the output only (operators,     ordered by executions of the statement), not the work before it. Permissions: VIEW SERVER STATE (2019) or VIEW     SERVER PERFORMANCE STATE (2022 and later); without it SQL Server raises a permission error (Msg 300).     Modules whose metadata the login cannot see appear as object_id.   - Part 3, modules: text search for the linked server names in procedures, functions, views and triggers of the     current database. Finds stored EXEC … AT, which does not appear in the plan cache, but also comments and similar     names (unverified). It misses ad hoc EXEC … AT and server names built at run time; use Extended Events on the     remote side for those. Permissions: the login must see the modules (VIEW DEFINITION).   - Scope of part 2: only plans that are in the cache right now and only statements executed at least once since     they were compiled. Missing: evicted plans, ad hoc plan stubs (optimize for ad hoc workloads), statements with     OPTION (RECOMPILE), plans that cannot be converted to xml (counted only) and EXEC … AT (not cached in the lab,     neither alone nor as INSERT … EXEC … AT). An empty list does not mean there is no linked server access.   - Columns of part 2:     access_form       four-part name (Remote Query or object in the remote operator), OPENQUERY/OPENROWSET                       (pass-through text in the remote operator), EXEC … AT (RemoteObject = STREAM).     linked_server     from RemoteSource: the name for four-part reads, otherwise the data source (data_source),                       mapped to the name through sys.servers; several names if they share a data source.     remote_text       RemoteQuery (Remote Query) or RemoteObject: the text A sends to the remote server, or the                       object. The actual plan and the text on the remote server remain the reference.     estimated_calls   1 + EstimateRebinds + EstimateRewinds: estimated executions of the operator per execution of                       the statement, e.g. once per outer row on the inner side of a nested loops.     note              patterns from the PSG lab (SQL Server to SQL Server via MSOLEDBSQL):                       - inner side of a loop: one remote call per outer row (estimated_calls > 1)                       - a filter above the remote access runs locally; without WHERE in the remote text probably                         the whole table (only the two operators above are checked; verify the actual rows in the                         actual plan)                       - Remote Insert/Update/Delete: suspected row-by-row writes, one remote call per row                       - fixed estimate of 10,000 rows for pass-through text     non_parallel_reason  NonParallelPlanReason of the statement plan, e.g. NoParallelWithRemoteQuery. NULL on 2019                          in the lab.*/SET NOCOUNT ON;SET QUOTED_IDENTIFIER ON; DECLARE @database    sysname = NULL;  -- NULL = all databases, else statements of this database onlyDECLARE @top_rows    int     = 100;   -- rows per part, part 2 ordered by executionsDECLARE @text_length int     = 200;   -- characters of statement and remote text IF @database IS NOT NULL AND DB_ID(@database) IS NULLBEGIN    RAISERROR(N'@database: database not found. Stopped, nothing was read.', 16, 1);    RETURN;END;DECLARE @db_id int = DB_ID(@database); -- Part 1: linked servers and options that change where filters runSELECT TOP (@top_rows)       N'1 linked servers'             AS part,       s.name                          AS linked_server,       s.provider,       s.data_source,       s.is_collation_compatible       AS collation_compatible,       s.uses_remote_collation         AS use_remote_collation,       s.collation_name,       s.lazy_schema_validation,       s.is_rpc_out_enabled            AS rpc_out,       s.is_remote_proc_transaction_promotion_enabled AS remote_proc_transaction_promotion,       CASE WHEN s.is_collation_compatible = 1            THEN N'collation compatible = true: SQL Server assumes the same collation without checking it; if they differ, results can be wrong'            WHEN s.uses_remote_collation = 0            THEN N'use remote collation = false: character comparisons ran locally in the lab and the whole table arrived (tested without collation name)'       END                             AS noteFROM sys.servers AS sWHERE s.is_linked = 1ORDER BY s.nameOPTION (MAXDOP 1); -- Part 2: statements with a remote operator in the plan cacheDROP TABLE IF EXISTS #psg_plans;DROP TABLE IF EXISTS #psg_findings;CREATE TABLE #psg_plans (    id int IDENTITY(1, 1) PRIMARY KEY, plan_handle varbinary(64) NOT NULL, database_name nvarchar(128) NULL,    object_type nvarchar(60) NULL, object_name nvarchar(400) NULL, statement_text nvarchar(max) NULL,    executions bigint NOT NULL, last_execution datetime NULL, x xml NULL);CREATE TABLE #psg_findings (    plan_id int NOT NULL, node_id int NULL, operator nvarchar(60) NULL, remote_source nvarchar(400) NULL,    remote_query nvarchar(max) NULL, remote_object nvarchar(max) NULL, estimated_rows float NULL,    estimated_calls float NULL, parent_op nvarchar(60) NULL, grandparent_op nvarchar(60) NULL,    non_parallel_reason nvarchar(200) NULL); INSERT #psg_plans (plan_handle, database_name, object_type, object_name, statement_text, executions, last_execution, x)SELECT qs.plan_handle,       DB_NAME(st.dbid),       CASE cp.objtype WHEN N'Adhoc' THEN N'ad hoc' WHEN N'Prepared' THEN N'prepared' WHEN N'Proc' THEN N'procedure'                       ELSE cp.objtype END,       CASE WHEN st.objectid IS NULL THEN N'-'            ELSE COALESCE(QUOTENAME(OBJECT_SCHEMA_NAME(st.objectid, st.dbid)) + N'.' + QUOTENAME(OBJECT_NAME(st.objectid, st.dbid)),                          CONCAT(N'object_id ', st.objectid)) END,       LEFT(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(st.text, qs.statement_start_offset / 2 + 1,            (CASE WHEN qs.statement_end_offset = -1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset END             - qs.statement_start_offset) / 2 + 1), NCHAR(13), N' '), NCHAR(10), N' '), NCHAR(9), N' ')), @text_length),       qs.execution_count,       qs.last_execution_time,       TRY_CONVERT(xml, tqp.query_plan)FROM sys.dm_exec_query_stats AS qsINNER JOIN sys.dm_exec_cached_plans AS cp ON cp.plan_handle = qs.plan_handleCROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) AS stCROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) AS tqpWHERE (@db_id IS NULL OR st.dbid = @db_id)  AND tqp.query_plan LIKE N'%PhysicalOp="Remote %'OPTION (MAXDOP 1); DECLARE @not_readable int = 0, @linked_visible int = 0;SELECT @not_readable = COUNT(*) FROM #psg_plans WHERE x IS NULL OPTION (MAXDOP 1);SELECT @linked_visible = COUNT(*) FROM sys.servers WHERE is_linked = 1 OPTION (MAXDOP 1); -- SQL Server XQuery has no starts-with(), hence contains()WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')INSERT #psg_findings (plan_id, node_id, operator, remote_source, remote_query, remote_object, estimated_rows,                      estimated_calls, parent_op, grandparent_op, non_parallel_reason)SELECT p.id,       r.op.value(N'(@NodeId)[1]', N'int'),       r.op.value(N'(@PhysicalOp)[1]', N'nvarchar(60)'),       r.op.value(N'(*/@RemoteSource)[1]', N'nvarchar(400)'),       r.op.value(N'(*/@RemoteQuery)[1]', N'nvarchar(max)'),       r.op.value(N'(*/@RemoteObject)[1]', N'nvarchar(max)'),       r.op.value(N'(@EstimateRows)[1]', N'float'),       1 + ISNULL(r.op.value(N'(@EstimateRebinds)[1]', N'float'), 0) + ISNULL(r.op.value(N'(@EstimateRewinds)[1]', N'float'), 0),       r.op.value(N'(../../@PhysicalOp)[1]', N'nvarchar(60)'),       r.op.value(N'(../../../../@PhysicalOp)[1]', N'nvarchar(60)'),       p.x.value(N'(//QueryPlan/@NonParallelPlanReason)[1]', N'nvarchar(200)')FROM #psg_plans AS pCROSS APPLY p.x.nodes(N'//RelOp[contains(@PhysicalOp, "Remote")]') AS r(op)WHERE p.x IS NOT NULLOPTION (MAXDOP 1); SELECT TOP (@top_rows)       N'2 plan cache'                 AS part,       p.database_name,       p.object_type,       p.object_name,       p.statement_text,       p.executions,       p.last_execution,       f.operator,       a.access_form,       COALESCE(n.linked_server, CASE WHEN f.operator = N'Remote Query' THEN f.remote_source END, N'?') AS linked_server,       f.remote_source,       LEFT(a.remote_text, @text_length) AS remote_text,       f.estimated_rows,       f.estimated_calls,       NULLIF(CONCAT(           CASE WHEN f.estimated_calls > 1                THEN N'inner side of a loop: one remote call per outer row; ' END,           CASE WHEN h.local_filter = 1 AND a.remote_text LIKE N'SELECT %' AND a.remote_text NOT LIKE N'% WHERE %'                THEN N'local filter, no WHERE in remote text: probably the whole table; '                WHEN h.local_filter = 1                THEN N'filter above the remote access runs locally (fully or partly); ' END,           CASE WHEN f.operator IN (N'Remote Insert', N'Remote Update', N'Remote Delete')                THEN N'suspect: writes row by row, one remote call per row; ' END,           CASE WHEN a.access_form <> N'four-part name' AND f.estimated_rows = 10000                THEN N'fixed estimate of 10,000 rows; ' END), N'') AS note,       f.non_parallel_reason,       CONVERT(varchar(130), p.plan_handle, 1) AS plan_handle,       f.node_idFROM #psg_findings AS fINNER JOIN #psg_plans AS p ON p.id = f.plan_idCROSS APPLY (SELECT CASE WHEN f.remote_object = N'STREAM'                         THEN N'EXEC … AT'                         WHEN f.operator = N'Remote Query'                        THEN N'four-part name'                         WHEN LEFT(LTRIM(f.remote_object), 1) IN (N'"', N'[')     THEN N'four-part name'                         ELSE N'OPENQUERY/OPENROWSET' END AS access_form,                    REPLACE(REPLACE(REPLACE(COALESCE(f.remote_query, f.remote_object), NCHAR(13), N' '), NCHAR(10), N' '),                            NCHAR(9), N' ') AS remote_text) AS aCROSS APPLY (SELECT CASE WHEN f.parent_op = N'Filter'                           OR (f.parent_op = N'Compute Scalar' AND f.grandparent_op = N'Filter') THEN 1 ELSE 0 END AS local_filter) AS hOUTER APPLY (SELECT STRING_AGG(CONVERT(nvarchar(max), s.name), N', ') WITHIN GROUP (ORDER BY s.name) AS linked_server             FROM sys.servers AS s             WHERE s.is_linked = 1 AND (s.name = f.remote_source OR s.data_source = f.remote_source)) AS nORDER BY p.executions DESC, p.database_name, p.object_name, p.statement_text, f.node_idOPTION (MAXDOP 1); IF @linked_visible = 0    PRINT N'Note: this login sees no linked server in sys.servers. Parts 1 and 3 stay empty; linked_server shows a name for four-part reads only.';IF @not_readable > 0    PRINT CONCAT(N'Note: ', @not_readable, N' statement plan(s) with a remote operator not convertible to xml (nested too deeply), not checked.'); -- Part 3: modules of the current database that contain a linked server name (text search)SELECT TOP (@top_rows)       N'3 modules ' + QUOTENAME(DB_NAME()) AS part,       QUOTENAME(OBJECT_SCHEMA_NAME(m.object_id)) + N'.' + QUOTENAME(OBJECT_NAME(m.object_id)) AS object_name,       o.type_desc                     AS object_type,       s.name                          AS linked_server,       NULLIF(CONCAT(           CASE WHEN d.t LIKE N'%OPENQUERY%(%' + e.m + N'%'                                  THEN N'OPENQUERY, ' END,           CASE WHEN d.t LIKE N'%) AT ' + e.m + N'%' OR d.t LIKE N'%) AT [[]' + e.m + N']%'                  OR d.t LIKE N'%)AT [[]' + e.m + N']%'                                           THEN N'EXEC … AT, ' END,           CASE WHEN d.t LIKE N'%' + e.m + N'.%' OR d.t LIKE N'%[[]' + e.m + N'].%'             THEN N'four-part name, ' END),           N'')                        AS found_forms,       N'text search, also in comments; unverified' AS noteFROM sys.sql_modules AS mINNER JOIN sys.objects AS o ON o.object_id = m.object_idCROSS APPLY (SELECT REPLACE(REPLACE(REPLACE(UPPER(m.definition), NCHAR(13), N' '), NCHAR(10), N' '), NCHAR(9), N' ') AS t) AS dINNER JOIN sys.servers AS s ON s.is_linked = 1-- COLLATE DATABASE_DEFAULT: sys.servers uses the instance collation, the modules the database collation (else Msg 468)CROSS APPLY (SELECT REPLACE(REPLACE(REPLACE(UPPER(s.name COLLATE DATABASE_DEFAULT), N'[', N'[[]'), N'_', N'[_]'), N'%', N'[%]') AS m) AS eWHERE d.t LIKE N'%' + e.m + N'%'ORDER BY object_name, s.nameOPTION (MAXDOP 1); DROP TABLE #psg_plans;DROP TABLE #psg_findings;

The plan cache part needs the permission VIEW SERVER STATE; from SQL Server 2022 on, VIEW SERVER PERFORMANCE STATE is enough. The module search needs to see the module definitions (VIEW DEFINITION). In the lab, a login without sysadmin and without its own linked server mapping saw no linked server in sys.servers. The parts on linked server options and on modules then stay empty, and the query says so at the end.

ColumnExample from the lab
access_formfour-part name
remote_textSELECT "Tbl1002"."OrderID" "Col1004" FROM "LinkedLab"."dbo"."Orders" "Tbl1002" WHERE ?="Tbl1002"."OrderID"
estimated_calls10
noteinner side of a loop: one remote call per outer row

An empty list doesn't mean there is no linked server access. The query only sees plans that are in the cache right now. Evicted plans, statements with OPTION (RECOMPILE) and every EXEC … AT are missing.

Rebuild the lab

  1. Set the password in script 1 and run it on the remote server.
  2. Set server, port and the same password in script 2 and run it on the local server.
  3. When you are done, run script 3 on both instances, the local one first.

If the placeholders stay in place or the objects already exist, scripts 1 and 2 stop with a message and change nothing. Script 3 only drops a database LinkedLab that carries the lab marker from script 1 or 2. The script comments are in German and English.

Script 1 on the remote server:

/* PSG · Linked Server · Aufbau 1 von 3: die Gegenseite (der Server mit den Daten)   Linked servers · setup 1 of 3: the remote side (the server that holds the data)   Stand / as of 27.11.2026 · getestet / tested: SQL Server 2022 CU27, 2025 CU10 (Linux-Container, Lab)    WARNUNG: Nur auf einem Testsystem ausführen. Vorher @passwort setzen. Das Skript legt die Datenbank LinkedLab mit   rund 1 Mio. Zeilen an (einige hundert MB inklusive Log), dazu den SQL-Login link_reader mit Leserechten auf Orders   und Schreibrechten auf zwei Testtabellen. Gibt es LinkedLab oder link_reader schon, bricht es ab, bevor es etwas   ändert. Mit dem Platzhalter oder nach einem Fehler führt es die folgenden Batches nicht mehr aus (SET NOEXEC ON).   Aufräumen: aufbau-3-aufraeumen.sql, es löscht nur die Datenbank mit der Lab-Kennung und den Login.   WARNING: Run it on a test system only. Set @passwort first. The script creates the database LinkedLab with about   1 million rows (a few hundred MB including the log) and the SQL login link_reader with read permission on Orders   and write permission on two test tables. If LinkedLab or link_reader already exist, it stops before it changes   anything. With the placeholder or after an error it does not run the following batches (SET NOEXEC ON).   Clean up: aufbau-3-aufraeumen.sql; it drops only the database with the lab marker and the login.    - Inhalt / contents: dbo.Orders (1.000.000 Zeilen, 10 mit CustomerCode = 'TARGET', CodeCS case-sensitiv mit 10 x     'TARGET' und 10 x 'target', 10 Zeilen im Jahr 2099), dbo.WriteTarget (100.000 Zeilen), dbo.InsertTarget (leer).   - Danach auf der lokalen Instanz aufbau-2-lokal.sql ausführen. / Then run aufbau-2-lokal.sql on the local instance.*/SET NOCOUNT ON; DECLARE @passwort nvarchar(128) = N'HIER-EIGENES-PASSWORT';  -- Passwort für link_reader / password for link_reader IF NULLIF(@passwort, N'') IS NULL OR @passwort = N'HIER-EIGENES-PASSWORT'BEGIN    RAISERROR(N'@passwort setzen. Abgebrochen, es wurde nichts angelegt. / Set @passwort. Stopped, nothing was created.', 16, 1);    SET NOEXEC ON;  -- folgende Batches nicht ausführen / do not run the following batchesENDELSE IF DB_ID(N'LinkedLab') IS NOT NULL OR SUSER_ID(N'link_reader') IS NOT NULLBEGIN    RAISERROR(N'LinkedLab oder link_reader gibt es schon. Abgebrochen, nichts geändert. / LinkedLab or link_reader already exists. Stopped, nothing changed.', 16, 1);    SET NOEXEC ON;ENDELSEBEGIN TRY    DECLARE @sql nvarchar(400) = N'CREATE LOGIN link_reader WITH PASSWORD = ' + QUOTENAME(@passwort, N'''') + N';';    EXEC sys.sp_executesql @sql;    CREATE DATABASE LinkedLab COLLATE Latin1_General_100_CI_AS;END TRYBEGIN CATCH    DECLARE @m nvarchar(2048) = ERROR_MESSAGE();    -- Die Vorprüfung hat gezeigt, dass es link_reader vorher nicht gab / the pre-check showed link_reader did not exist    IF SUSER_ID(N'link_reader') IS NOT NULL AND DB_ID(N'LinkedLab') IS NULL        DROP LOGIN link_reader;    RAISERROR(N'Aufbau abgebrochen / setup stopped: %s', 16, 1, @m);    SET NOEXEC ON;END CATCH;GO USE LinkedLab;GO BEGIN TRY    -- Lab-Kennung, auf die aufbau-3-aufraeumen.sql prüft / lab marker checked by aufbau-3-aufraeumen.sql    EXEC sys.sp_addextendedproperty @name = N'psg_lab', @value = N'linked-server-gegenseite';     CREATE TABLE dbo.Orders (        OrderID      int          NOT NULL PRIMARY KEY,        CustomerCode varchar(16)  NOT NULL,        CodeCS       varchar(16)  COLLATE Latin1_General_100_CS_AS NOT NULL,  -- case-sensitiv / case-sensitive        CreatedAt    datetime2(0) NOT NULL,        Status       tinyint      NOT NULL,        Amount       decimal(12,2) NOT NULL,        Note         varchar(100) NOT NULL);     WITH digits(d) AS (SELECT d FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS v(d)),    ids AS (        SELECT 1 + a.d + 10 * b.d + 100 * c.d + 1000 * d.d + 10000 * e.d + 100000 * f.d AS n        FROM digits AS a CROSS JOIN digits AS b CROSS JOIN digits AS c        CROSS JOIN digits AS d CROSS JOIN digits AS e CROSS JOIN digits AS f)    INSERT dbo.Orders WITH (TABLOCK)    SELECT n,           CASE WHEN n <= 10 THEN 'TARGET' ELSE CONCAT('C', n % 100000) END,           CASE WHEN n <= 10 THEN 'TARGET' WHEN n <= 20 THEN 'target' ELSE CONCAT('X', n) END,           CASE WHEN n <= 10 THEN CAST('2099-01-01' AS datetime2(0))                ELSE DATEADD(second, n, CAST('2020-01-01' AS datetime2(0))) END,           n % 5,           n % 1000 + 0.5,           REPLICATE('x', 80)    FROM ids;     CREATE INDEX IX_Orders_CustomerCode ON dbo.Orders (CustomerCode);    CREATE INDEX IX_Orders_CodeCS ON dbo.Orders (CodeCS);    CREATE INDEX IX_Orders_CreatedAt ON dbo.Orders (CreatedAt);     CREATE TABLE dbo.WriteTarget (ID int NOT NULL PRIMARY KEY, Code varchar(16) NOT NULL,                                  Amount decimal(12,2) NOT NULL, Note varchar(100) NOT NULL);    CREATE TABLE dbo.InsertTarget (ID int NOT NULL PRIMARY KEY, Code varchar(16) NOT NULL,                                   Amount decimal(12,2) NOT NULL, Note varchar(100) NOT NULL);     -- Ausgangsstand der Schreibtabellen; der Artikel zeigt den Reset vor jedem Schreibbeispiel    -- initial state of the write tables; the article shows the reset before each write example    INSERT dbo.WriteTarget (ID, Code, Amount, Note)    SELECT OrderID, CustomerCode, Amount, Note FROM dbo.Orders WHERE OrderID <= 100000;     CREATE USER link_reader FOR LOGIN link_reader;    GRANT SELECT ON dbo.Orders TO link_reader;    GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.WriteTarget TO link_reader;    GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.InsertTarget TO link_reader;    ALTER LOGIN link_reader WITH DEFAULT_DATABASE = LinkedLab;END TRYBEGIN CATCH    DECLARE @m nvarchar(2048) = ERROR_MESSAGE();    RAISERROR(N'Aufbau abgebrochen / setup stopped: %s', 16, 1, @m);    SET NOEXEC ON;END CATCH; SELECT COUNT_BIG(*)                                             AS orders,     -- 1000000       SUM(CASE WHEN CustomerCode = 'TARGET' THEN 1 ELSE 0 END) AS target_ci,  -- 10       SUM(CASE WHEN CodeCS = 'TARGET' THEN 1 ELSE 0 END)       AS target_cs   -- 10FROM dbo.Orders;GO SET NOEXEC OFF;GO

Script 2 on the local server:

/* PSG · Linked Server · Aufbau 2 von 3: die lokale Instanz (der Server, der abfragt)   Linked servers · setup 2 of 3: the local instance (the server that runs the queries)   Stand / as of 27.11.2026 · getestet / tested: SQL Server 2022 CU27, 2025 CU10 (Linux-Container, Lab)    WARNUNG: Nur auf einem Testsystem ausführen. Vorher @gegenseite und @passwort setzen (Passwort aus   aufbau-1-gegenseite.sql). Das Skript legt den Linked Server LS_Remote und die Datenbank LinkedLab mit   Schlüsseltabellen an. LS_Remote meldet sich auf der Gegenseite als link_reader an, und zwar nur für den Login,   der dieses Skript ausführt (SUSER_SNAME()); andere Logins können LS_Remote nicht benutzen. Gibt es LS_Remote oder   LinkedLab schon, bricht es ab, bevor es etwas ändert. Mit Platzhaltern oder nach einem Fehler führt es die   folgenden Batches nicht mehr aus (SET NOEXEC ON). Aufräumen: aufbau-3-aufraeumen.sql.   WARNING: Run it on a test system only. Set @gegenseite and @passwort first (password from aufbau-1-gegenseite.sql).   The script creates the linked server LS_Remote and the database LinkedLab with key tables. LS_Remote signs in on   the remote side as link_reader, for the login that runs this script only (SUSER_SNAME()); other logins cannot use   LS_Remote. If LS_Remote or LinkedLab already exist, it stops before it changes anything. With placeholders or   after an error it does not run the following batches (SET NOEXEC ON). Clean up: aufbau-3-aufraeumen.sql.    - Provider MSOLEDBSQL (OLE DB Driver for SQL Server). TrustServerCertificate=Yes nur im Testlab, mit gültigem     Zertifikat weglassen. MSOLEDBSQL 18 (z. B. SQL Server 2019 und 2022) erwartet Encrypt=Yes statt Mandatory.     TrustServerCertificate=Yes in a test lab only; omit it with a valid certificate. MSOLEDBSQL 18 (e.g. SQL Server     2019 and 2022) expects Encrypt=Yes instead of Mandatory.   - Serveroptionen bleiben auf dem Standard (collation compatible = false, use remote collation = true, remote proc     transaction promotion = true), nur rpc out = true für EXEC … AT.     Server options stay at their defaults, only rpc out = true for EXEC … AT.   - Inhalt / contents: dbo.FilterIDs10, dbo.FilterIDs1000, dbo.FilterIDs10000 (Vielfache von 7 / multiples of 7),     dbo.FilterIDs3000, dbo.FilterIDs30000 (gleichmäßig über 1 bis 1.000.000 verteilt / spread evenly),     dbo.fnNorm (inline-fähig) und dbo.fnNormNoInline (WITH INLINE = OFF, ab SQL Server 2019).*/SET NOCOUNT ON; DECLARE @gegenseite      nvarchar(256) = N'SQLSRV-02,1433';                       -- Server und Port der Gegenseite / remote server and portDECLARE @passwort        nvarchar(128) = N'HIER-EIGENES-PASSWORT';                -- Passwort von link_reader / password of link_readerDECLARE @verschluesselung nvarchar(200) = N'Encrypt=Mandatory;TrustServerCertificate=Yes';  -- siehe Kopf / see headerDECLARE @ich             sysname       = SUSER_SNAME(); IF NULLIF(@gegenseite, N'') IS NULL OR NULLIF(@passwort, N'') IS NULL   OR @gegenseite = N'SQLSRV-02,1433' OR @passwort = N'HIER-EIGENES-PASSWORT'BEGIN    RAISERROR(N'@gegenseite und @passwort setzen. Abgebrochen, es wurde nichts angelegt. / Set @gegenseite and @passwort. Stopped, nothing was created.', 16, 1);    SET NOEXEC ON;  -- folgende Batches nicht ausführen / do not run the following batchesENDELSE IF EXISTS (SELECT 1 FROM sys.servers WHERE name = N'LS_Remote') OR DB_ID(N'LinkedLab') IS NOT NULLBEGIN    RAISERROR(N'LS_Remote oder LinkedLab gibt es schon. Abgebrochen, nichts geändert. / LS_Remote or LinkedLab already exists. Stopped, nothing changed.', 16, 1);    SET NOEXEC ON;ENDELSEBEGIN TRY    EXEC sys.sp_addlinkedserver @server = N'LS_Remote', @srvproduct = N'', @provider = N'MSOLEDBSQL',         @datasrc = @gegenseite, @provstr = @verschluesselung;    EXEC sys.sp_droplinkedsrvlogin @rmtsrvname = N'LS_Remote', @locallogin = NULL;  -- keine Anmeldung für alle / no mapping for everyone    EXEC sys.sp_addlinkedsrvlogin @rmtsrvname = N'LS_Remote', @useself = N'False', @locallogin = @ich,         @rmtuser = N'link_reader', @rmtpassword = @passwort;    EXEC sys.sp_serveroption N'LS_Remote', N'rpc out', N'true';    EXEC sys.sp_testlinkedserver N'LS_Remote';    CREATE DATABASE LinkedLab COLLATE Latin1_General_100_CI_AS;END TRYBEGIN CATCH    DECLARE @m nvarchar(2048) = ERROR_MESSAGE();    -- Die Vorprüfung hat gezeigt, dass es LS_Remote vorher nicht gab: halb Angelegtes wieder entfernen    -- the pre-check showed LS_Remote did not exist before: remove what was half created    IF EXISTS (SELECT 1 FROM sys.servers WHERE name = N'LS_Remote')        EXEC sys.sp_dropserver @server = N'LS_Remote', @droplogins = 'droplogins';    RAISERROR(N'Aufbau abgebrochen / setup stopped: %s', 16, 1, @m);    SET NOEXEC ON;END CATCH;GO USE LinkedLab;GO BEGIN TRY-- Lab-Kennung, auf die aufbau-3-aufraeumen.sql prüft / lab marker checked by aufbau-3-aufraeumen.sqlEXEC sys.sp_addextendedproperty @name = N'psg_lab', @value = N'linked-server-lokal'; WITH digits(d) AS (SELECT d FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS v(d)),ids AS (    SELECT 1 + a.d + 10 * b.d + 100 * c.d + 1000 * d.d AS n    FROM digits AS a CROSS JOIN digits AS b CROSS JOIN digits AS c CROSS JOIN digits AS d)SELECT ItemID = CAST(n * 7 AS int) INTO dbo.FilterIDs10000 FROM ids WHERE n <= 10000; ALTER TABLE dbo.FilterIDs10000 ALTER COLUMN ItemID int NOT NULL;ALTER TABLE dbo.FilterIDs10000 ADD PRIMARY KEY (ItemID);SELECT ItemID INTO dbo.FilterIDs1000 FROM dbo.FilterIDs10000 WHERE ItemID <= 7000;ALTER TABLE dbo.FilterIDs1000 ADD PRIMARY KEY (ItemID);SELECT ItemID INTO dbo.FilterIDs10 FROM dbo.FilterIDs10000 WHERE ItemID <= 70;ALTER TABLE dbo.FilterIDs10 ADD PRIMARY KEY (ItemID); -- k Schlüssel gleichmäßig über 1 bis 1.000.000 / k keys spread evenly over 1 to 1,000,000SELECT ItemID = CAST(n * (1000000 / 3000) AS int) INTO dbo.FilterIDs3000FROM (SELECT TOP (3000) n = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))      FROM sys.all_columns AS a CROSS JOIN sys.all_columns AS b) AS t;ALTER TABLE dbo.FilterIDs3000 ALTER COLUMN ItemID int NOT NULL;ALTER TABLE dbo.FilterIDs3000 ADD PRIMARY KEY (ItemID);SELECT ItemID = CAST(n * (1000000 / 30000) AS int) INTO dbo.FilterIDs30000FROM (SELECT TOP (30000) n = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))      FROM sys.all_columns AS a CROSS JOIN sys.all_columns AS b) AS t;ALTER TABLE dbo.FilterIDs30000 ALTER COLUMN ItemID int NOT NULL;ALTER TABLE dbo.FilterIDs30000 ADD PRIMARY KEY (ItemID);END TRYBEGIN CATCH    DECLARE @m nvarchar(2048) = ERROR_MESSAGE();    RAISERROR(N'Aufbau abgebrochen / setup stopped: %s', 16, 1, @m);    SET NOEXEC ON;END CATCH;GO CREATE FUNCTION dbo.fnNorm (@s varchar(16)) RETURNS varchar(16)AS BEGIN RETURN UPPER(@s); END;GO CREATE FUNCTION dbo.fnNormNoInline (@s varchar(16)) RETURNS varchar(16) WITH INLINE = OFFAS BEGIN RETURN UPPER(@s); END;GO SELECT (SELECT COUNT(*) FROM dbo.FilterIDs10)    AS ids_10,       (SELECT COUNT(*) FROM dbo.FilterIDs1000)  AS ids_1000,       (SELECT COUNT(*) FROM dbo.FilterIDs3000)  AS ids_3000,       (SELECT COUNT(*) FROM dbo.FilterIDs10000) AS ids_10000,       (SELECT COUNT(*) FROM dbo.FilterIDs30000) AS ids_30000,       (SELECT COUNT_BIG(*) FROM LS_Remote.LinkedLab.dbo.Orders) AS remote_orders;  -- 1000000GO SET NOEXEC OFF;GO

Script 3 to clean up:

/* PSG · Linked Server · Aufbau 3 von 3: aufräumen   Linked servers · setup 3 of 3: clean up   Stand / as of 27.11.2026 · getestet / tested: SQL Server 2022 CU27, 2025 CU10 (Linux-Container, Lab)    WARNUNG: Auf beiden Instanzen ausführen, zuerst auf der lokalen, dann auf der Gegenseite. Das Skript löscht die   Datenbank LinkedLab samt Inhalt endgültig und trennt dafür alle Sitzungen in dieser Datenbank (ROLLBACK   IMMEDIATE). Auf der lokalen Instanz löscht es zusätzlich den Linked Server LS_Remote, auf der Gegenseite den Login   link_reader. Es löscht nur, wenn LinkedLab die Lab-Kennung aus aufbau-1 bzw. aufbau-2 trägt; sonst bricht es ab   und ändert nichts.   WARNING: Run it on both instances, first on the local one, then on the remote side. The script drops the database   LinkedLab with all its contents for good and disconnects every session in it (ROLLBACK IMMEDIATE). On the local   instance it also drops the linked server LS_Remote, on the remote side the login link_reader. It drops only if   LinkedLab carries the lab marker from aufbau-1 or aufbau-2; otherwise it stops and changes nothing.*/SET NOCOUNT ON;USE master; DECLARE @kennung nvarchar(100) = NULL;IF DB_ID(N'LinkedLab') IS NOT NULL    SELECT @kennung = CAST(value AS nvarchar(100))    FROM LinkedLab.sys.extended_properties    WHERE class = 0 AND name = N'psg_lab'; IF @kennung IS NULLBEGIN    RAISERROR(N'Keine Datenbank LinkedLab mit Lab-Kennung gefunden. Abgebrochen, nichts gelöscht. / No database LinkedLab with lab marker found. Stopped, nothing dropped.', 16, 1);    RETURN;END; IF @kennung = N'linked-server-lokal'   AND EXISTS (SELECT 1 FROM sys.servers WHERE name = N'LS_Remote' AND is_linked = 1)    EXEC sys.sp_dropserver @server = N'LS_Remote', @droplogins = 'droplogins'; ALTER DATABASE LinkedLab SET SINGLE_USER WITH ROLLBACK IMMEDIATE;DROP DATABASE LinkedLab; IF @kennung = N'linked-server-gegenseite' AND SUSER_ID(N'link_reader') IS NOT NULL    DROP LOGIN link_reader; SELECT CONCAT(N'Aufgeräumt / cleaned up: ', @kennung) AS ergebnis;GO

What the test shows and what it doesn't

  • Setup: two SQL Server instances in Linux containers, each with two dedicated CPUs and 2,048 MB max server memory. Connection from SQL Server to SQL Server through MSOLEDBSQL 19 (on 2022: 18) with a SQL login. Synthetic data: 1 million rows, about 130 bytes per row.
  • Latency: artificially added, 1 ms or 5 ms in each direction (2 ms or 10 ms RTT), without limiting bandwidth. Without it, the path between the containers took a few tenths of a millisecond.
  • Numbers: medians of three runs on SQL Server 2025 CU10, read cases with the plan in cache. The cases on COLLATE, AND and OR come from a follow-up run with one run each without and with the plan in cache, without times. The ranges were mostly below 5 %. Rows, remote calls and remote texts were the same in all repetitions. On 2022 CU27 the same patterns showed up; we did not evaluate the times there.
  • Times: measured at the client, including about 0.25 s for starting the tool. What transfers to other systems are the ratios and the cost per row and remote call, not the absolute values.
  • Not tested: Windows instances and Windows authentication, other providers, a SQL collation on the remote server, larger remote tables for the threshold, and distributed transactions in other environments. MSDTC was not specifically configured in the containers.

Sources