| Lesson 7 | Using OPENROWSET |
| Objective | Use OPENROWSET to read remote SQL Server tables and distinguish remote queries from BULK file reads. |
OPENROWSET is a built-in Transact-SQL rowset function. It lets a query obtain external data and use the returned rows in its FROM clause. For an occasional query against another SQL Server instance, you can supply an OLE DB provider, connection information, and remote SQL directly in the statement. You do not first need to create a linked-server definition.
This lesson develops a read-only example for SQL Server 2025 on Windows. You will inspect the local configuration, identify the correct provider, and retrieve selected orders from a remote database. You will also compare the table-name form with pass-through SQL and learn why OPENROWSET(BULK...) is a different operation. The examples assume an administrator has approved the required access.
Suppose your SSMS query window is connected to instance A. The requested Orders table belongs to instance B. When you submit the example, A loads the provider and connects to B; your workstation does not fetch B's rows on A's behalf. B evaluates the supplied remote query, A processes its returned rowset, and the final result travels back to SSMS.
This route explains several common setup mistakes. Installing a driver only on your workstation does not install it for A. A must be able to resolve and reach B's endpoint. The outgoing connection also needs an authenticated identity that B accepts. A successful direct SSMS connection from your workstation to B does not by itself prove that this additional connection will succeed.
Creating an SSMS Registered Servers entry only saves client connection information. Likewise, the RemoteB linked-server name introduced in earlier lessons is a local configuration name. This example instead places a server endpoint in its connection string. It creates neither that linked-server definition nor a login mapping through sp_addlinkedsrvlogin.
Use the following assumptions when adapting the SQL. These names describe a teaching scenario, not tables installed automatically with SQL Server:
| Component | Example value or requirement |
|---|---|
| Local instance | A, running SQL Server 2025 on Windows |
| Remote endpoint | sql-b.example.com, a placeholder for B's actual address |
| Remote object | SalesDB.dbo.Orders |
| Columns | Integer OrderID and CustomerID; OrderID is unique |
| Requested rows | Up to 20 orders for customer 42, ordered by OrderID |
| Remote authorization | The effective identity can access SalesDB and SELECT from dbo.Orders |
Replace the endpoint and object names with your lab's values. Verify the table's actual column names and types before adapting its predicate. If your customer identifiers are strings, for example, the numeric literal used here is not an appropriate substitute. These SQL examples illustrate the documented interfaces; no sample result rows or successful execution are assumed.
The first OPENROWSET argument identifies the installed OLE DB provider. For Microsoft OLE DB Driver 19, its ProgID is MSOLEDBSQL19. Driver 18 uses MSOLEDBSQL, and the two versions can be installed side by side. The examples below explicitly select version 19. Check the provider registered on A rather than assuming a generic provider name means the newest installed version. Microsoft lists these identifiers in its driver component documentation.
For new development, use the maintained Microsoft OLE DB driver rather than copying old examples based on SQLNCLI, SQLNCLI11, or SQLOLEDB. Driver selection and database-engine version are related deployment choices, but they are not interchangeable names. Record the selected driver version when diagnosing differences between two servers. Microsoft's installation-check guidance helps establish what is actually installed.
Remote OLE DB access requires both the instance configuration and the selected provider's access policy to permit it. Ad Hoc Distributed Queries is disabled by default. The provider must also have DisallowAdhocAccess explicitly set to 0. Changing the instance option alone does not establish either remote authentication or permission to read a table. See Microsoft's provider access requirements.
Apply this reasoning to the direction of access: A is opening the external connection, so inspect A's settings. Enabling the option on B does not enable A's outgoing request. B still controls authentication and authorization for its own data. If you later reverse the example and query A from B, reassess the configuration and identity from that new starting point.
Begin with a diagnostic query on A. It reads configuration metadata without changing settings:
SELECT name, value AS configured_value, value_in_use
FROM sys.configurations
WHERE name IN ('show advanced options', 'Ad Hoc Distributed Queries');
configured_value reports the configured value; value_in_use reports the value currently in effect. Checking both avoids treating a requested setting as proof of the running state. Save these values before an administrator makes a change. The definitions come from the sys.configurations catalog view.
If ad hoc access is approved and needs enabling, an administrator can perform this instance-level setup:
-- Administrator setup on local instance A, when required.
USE master;
GO
EXEC sys.sp_configure N'show advanced options', 1;
RECONFIGURE;
EXEC sys.sp_configure N'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
show advanced options exposes advanced settings to sp_configure. RECONFIGURE applies configuration changes; changing these settings requires appropriate server-level authority. This is administrative setup, not a preamble that every application query should execute. Consult the sp_configure reference for its permission requirements.
Restore the original visibility setting afterward if this work changed it. Do not assume its previous value was 0. Coordinate any later disabling of ad hoc access with other users who depend on it. Microsoft's configuration guidance explains that enabling ad hoc names makes the provider accessible to authenticated local accounts. Remote authorization still applies. An organization that prohibits this access should choose an approved integration route.
The examples use Windows authentication through Trusted_Connection=yes. In a client-to-A-to-B connection, A does not automatically forward the client's Windows identity. Delegation must be configured for that route; Windows environments commonly require suitable Kerberos and service-principal configuration. Have the administrator establish which identity reaches B instead of assuming that a successful login to A grants remote access.
The connection string deliberately includes Encrypt=Mandatory;TrustServerCertificate=no;. Driver 19 defaults to mandatory encryption, and these values make the intended behavior explicit. B needs a suitable certificate, its name must match the endpoint being used, and A must trust its certificate chain. A certificate-validation failure should lead to checking the name and trust configuration. See Microsoft's Driver 19 migration guidance.
OPENROWSET passes a provider string, whose keywords include Server, Database, Trusted_Connection, Encrypt, and TrustServerCertificate. Other interfaces, including ADO initialization strings, use different spellings for some properties. Use the relevant provider-string keyword documentation rather than mixing connection formats.
No SQL-login password is embedded in this lesson's queries. If your environment requires SQL authentication, have its credential handling reviewed separately. A password placed in a statement can be copied into saved scripts or operational records. Changing the authentication method also changes the identity whose remote permissions must be checked.
After setup, execute the following SELECT while connected to A. Its third argument contains the SQL submitted to B:
SELECT r.OrderID, r.CustomerID
FROM OPENROWSET(
'MSOLEDBSQL19',
'Server=sql-b.example.com;Database=SalesDB;Trusted_Connection=yes;Encrypt=Mandatory;TrustServerCertificate=no;',
'SELECT TOP (20) OrderID, CustomerID
FROM SalesDB.dbo.Orders
WHERE CustomerID = 42
ORDER BY OrderID'
) AS r
ORDER BY r.OrderID;
Read this example from the inside outward. The remote SELECT names two columns and restricts customer 42's orders. TOP (20) limits the returned subset. Because OrderID is unique in the example, the inner ordering identifies which 20 orders to choose when more are available. Fewer than 20 rows, including none, can be a valid result.
The alias r names the returned rowset for the outer SELECT. Its separate ORDER BY specifies the final presentation order. Do not rely on an inner ordering to promise the order of an outer query's results. Microsoft recommends combining TOP with ORDER BY when the selected subset must be predictable in its TOP documentation.
The connection's database setting and the qualified SalesDB.dbo.Orders reference make the destination explicit. The connection string remains one string literal; the line containing it may scroll horizontally. A linked-server alias is unnecessary here because the connection details are supplied directly.
Consider three possible outcomes. An authentication failure means the intended rowset was never obtained. A successful query returning no rows means the statement completed but found no qualifying rows visible to that execution. Twenty returned rows mean the limit was reached; they do not establish that customer 42 has exactly 20 orders. These distinctions matter when using a small inspection query to investigate a business-data problem.
Also distinguish a database name from an object name when adapting the example. Database=SalesDB sets the connection's initial database, while SalesDB.dbo.Orders identifies the object referenced by the remote SQL. Changing only one can leave your script describing two different databases. Keep both values consistent unless you deliberately need a connection context different from the qualified object's database.
You can instead identify the remote table as the third argument and place the filter in the surrounding SELECT:
SELECT TOP (20) r.OrderID, r.CustomerID
FROM OPENROWSET(
'MSOLEDBSQL19',
'Server=sql-b.example.com;Database=SalesDB;Trusted_Connection=yes;Encrypt=Mandatory;TrustServerCertificate=no;',
SalesDB.dbo.Orders
) AS r
WHERE r.CustomerID = 42
ORDER BY r.OrderID;
Notice that the table reference is an object name, not quoted SQL text. For this SQL Server source, include the database and schema as shown. The rowset still has an alias, but the predicate and row limit now belong to the outer statement. The two examples express the same requested subset for unchanged data; their execution strategies need not be identical.
Do not assume the outer predicate or TOP is always sent to B. When performance matters, inspect the actual execution plan and remote workload. The pass-through example places its filtering explicitly in the command submitted to B, which makes that part of the request easy to understand. It does not guarantee a particular index choice, execution time, or amount of physical I/O.
For a useful comparison, keep the requested columns, filter, ordering, and source data comparable. Measure elapsed time and examine the work performed on B, rather than judging efficiency from the number of rows displayed in SSMS. Returning 20 rows does not mean the remote engine examined only 20 rows. Table size, indexes, competing activity, and network conditions can all affect the observed result.
Run comparisons in a suitable test environment. Two executions against changing business data can legitimately return different orders, so a result difference alone does not prove one syntax is incorrect. Record when you ran each query and which environment and identity you used. That context makes a later performance or correctness investigation reproducible.
OPENROWSET arguments do not accept T-SQL variables. Replacing the connection literal with @ConnectionString, or the remote query with @Query, is not direct parameterization. Do not work around that restriction by casually concatenating user input into dynamic SQL. For an application requiring changing values, evaluate an interface that supports the required parameters and authorization model.
The alternative datasource/user/password syntax uses three separately quoted constants separated by semicolons. A single literal such as 'datasource;user;password' is not equivalent. The examples here use the clearer keyword/value provider-string form. Also, OPENROWSET returns only the first result set, so avoid designing the remote command around multiple independent SELECT results. These rules are documented in the OPENROWSET reference.
OPENROWSET(BULK...) uses a built-in bulk provider to read files. It does not use the MSOLEDBSQL19 connection shown above. The following example reads an existing file as bytes and returns one row with one column:
-- Read existing file bytes; no row is inserted into a table.
SELECT f.BulkColumn AS FileBytes
FROM OPENROWSET(
BULK 'C:\data\sample.txt',
SINGLE_BLOB
) AS f;
| Option | Returned SQL type | Interpretation |
|---|---|---|
SINGLE_BLOB | varbinary(max) | Binary contents |
SINGLE_CLOB | varchar(max) | Character data with the applicable encoding |
SINGLE_NCLOB | nvarchar(max) | Unicode character data |
A .txt extension does not make SINGLE_BLOB return text. Choose a text-reading option with attention to the file's encoding. This SELECT reads a rowset; persisting it requires a separate operation such as INSERT...SELECT. Reading a CSV file as one value also does not parse its records into typed columns. File parsing needs its own schema and format choices. See the OPENROWSET BULK reference.
The example path belongs to the machine running the database engine, not your SSMS workstation. Bulk-operation permissions and file access rights are required. Which operating-system identity accesses a file depends on authentication; it is not invariably the SQL Server service account. A network-share path introduces additional access requirements. Microsoft's bulk-import security guidance explains these contexts. Do not enable arbitrary external OLE DB providers merely to perform this built-in file operation.
Work from setup toward the requested object. This avoids treating every failure as a SQL syntax error or granting broader permissions than the task requires:
Record the complete provider message and the stage where the failure occurs. A connection rejected before authentication needs a different investigation from a valid connection that cannot read Orders. Change one relevant condition at a time and rerun the smallest query needed to establish whether that condition was responsible.
For example, if the provider cannot be loaded, editing the customer filter will not address the cause. If certificate validation fails, switching to an administrator login does not repair the certificate. If the connection succeeds but the object cannot be resolved, compare the database and schema with the actual remote definition before changing permissions. Match the corrective action to the evidence.
OPENROWSET is useful for an occasional, approved remote query whose connection details belong in the statement. For repeated access, Microsoft's configuration guidance recommends defining a linked server. That choice gives the connection and login mappings a persistent administrative location. It does not guarantee that every query becomes faster or that remote permissions are automatically correct.
When comparing approaches, consider who maintains the connection, how identities are authorized, how often the query runs, and what happens when the remote service is unavailable. For a periodic data transfer, a managed loading process may suit the job; for a live lookup, a remote query may be appropriate. Evaluate the actual workload rather than treating the age of a function as a reason to discard it.
The previous lesson's remote procedure and join examples use a configured linked server. This lesson supplied the connection inside OPENROWSET. Next, the OPENQUERY function combines pass-through SQL with an existing linked-server definition, letting you compare where connection management belongs.