Wednesday, June 12, 2024
HomeProductsSQL Server ToolsHow to Use OPENQUERY in SQL Server

How to Use OPENQUERY in SQL Server

We are thrilled to share the exciting news that our dbForge tools now support SQL OPENQUERY, a powerful SQL Server feature. With this integration, our users can take full advantage of this feature’s capabilities, enabling seamless execution of queries on remote data sources directly from our tools.

In this article, we will provide a comprehensive overview of OPENQUERY, a powerful SQL Server feature that enables seamless execution of queries on remote data sources. We will guide you through the process of setting up a linked server, a critical step to facilitate interaction with external databases. Furthermore, we will explore the practical applications of OPENQUERY for various data operations, demonstrating its versatility in fetching and manipulating data across different data sources. We will also examine how to handle potential errors when using OPENQUERY and provide an overview of its performance peculiarities.

Whether you are an experienced SQL Server specialist or a beginner just starting your database journey, this article aims to equip you with valuable insights into harnessing the full potential of OPENQUERY in SQL Server.

Download SQL Complete

Contents

Understanding OPENQUERY

OPENQUERY serves as a gateway for accessing data stored on external servers, allowing SQL Server to interact with different databases across the network.

The key concept behind OPENQUERY is the establishment of a linked server, which acts as a bridge between the local SQL Server instance and the remote data source. Once the linked server is set up, OPENQUERY enables the execution of SQL statements on the remote server directly from within SQL Server, as if the data were local.

The syntax for using OPENQUERY is straightforward:

SELECT * FROM OPENQUERY (LinkedServer, 'T-SQL Query')

Where:
LinkedServer is the name of the linked server.
T-SQL Query
is the T-SQL code that you want to execute on the remote server.

Using OPENQUERY, users can efficiently retrieve data from various data sources without the need for complex data migration or manual data transfers. It is particularly valuable in scenarios where data resides in separate databases, perhaps hosted on different database management systems.

However, it is essential to exercise caution when working with OPENQUERY, as it involves network communication and might introduce additional overhead. Users should carefully consider performance implications and possible security risks before utilizing this feature.

Important facts about OPENQUERY

  • The OPENQUERY function is an ad-hoc method to access data from a remote server. However, if you frequently query the remote server, it is advisable to utilize linked servers instead.
  • Parameters in the OPENQUERY function are not supported, and it cannot be used for executing extended stored procedures on linked servers.
  • When using OPENQUERY to access remote data, SQL Server forwards the query to the remote server. Such operations as parsing the query and generating the execution plan are carried out on the remote server.
  • In terms of performance, OPENQUERY tends to outperform linked servers. This is because linked servers involve breaking the query into local and remote queries. The local queries are executed on the local server, while the remote queries are sent to the remote server. SQL Server then combines the result sets and returns the final result set.

Setting up a linked server using the ODBC driver

By configuring a linked server, you can access and query data from the remote server as if it were part of your local SQL Server instance. Setting up a linked server using the ODBC driver enables SQL Server to establish a direct connection with external data sources like Oracle databases, for example. The ODBC driver facilitates data exchange and allows SQL Server to query and access the remote data as if it were located in its own environment.

To establish a linked server using the ODBC driver in SQL Server, you’ll first need to install and configure the ODBC driver on the machine with the local SQL Server. Afterward, you can proceed to link the remote server in SSMS to enable interaction with the remote database.

Install and configure the ODBC driver

In the given worked example, we will be establishing a link with a remote Oracle database, using the Oracle ODBC driver for this purpose.

1. Download Devart ODBC driver for Oracle.

2. Install the driver by launching the downloaded file and following the installation wizard instructions.

3. After the successful installation, access the ODBC Data Source Administrator utility on your machine. You can find it by searching for “ODBC Data Sources” in the Start menu.

4. On the System DSN tab, click Add to create a new data source.

 Add a new data source

5. In the Create New Data Source dialog that opens, select Devart ODBC driver for Oracle and click Finish.

Select Devart ODBC driver for Oracle

6. In the Devart ODBC driver for Oracle Configuration dialog, provide a name for the data source and input the necessary details, such as the server name or IP address, port number, database name, and user credentials.

Configure Devart ODBC driver for Oracle

7. Click Test Connection to confirm that the ODBC driver is correctly installed and configured.

8. If the test is successful, click OK to save the data source. You can now use this data source to connect to the Oracle server from other environments, such as SQL Server.

Configure the linked server in SSMS

1. Open SQL Server Management Studio (SSMS) and connect to the local SQL Server instance where you want to configure the linked server.

2. In the Object Explorer pane, expand the Server Objects node, right-click Linked Servers, and select New Linked Server from the context menu.

How to set up a Linked Server

3 In the New Linked Server dialog, provide the necessary configurations for the linked server. Once done, click OK to save the linked server configuration.

Linked server configuration

Note
When you choose the Microsoft OLE DB Provider for ODBC Drivers, it will use the ODBC driver that is configured in the ODBC Data Source Administrator on your system. In our case, it is Devart ODBC driver for Oracle.

To make sure that the linking process was successful, expand the corresponding node in Object Explorer. You will be able to see the database tables associated with the linked server.

Linked Server in SSMS

Once you have configured the linked server, you can use it to access the remote database from SQL Server. In this scenario, it’s the BicycleStoreDev database residing on Oracle.

Using OPENQUERY for data operations

SQL Complete, a powerful add-in for SSMS designed to enrich coding experience, fully supports the OPENQUERY syntax, providing autocomplete functionality and displaying informative tooltips when hovering over the keyword. This enhancement simplifies and streamlines the process of working with OPENQUERY statements, making it more efficient and user-friendly for developers. Let us look at its capabilities through the following examples.

Example 1: SELECT

First, let’s attempt to execute the SELECT statement on the remote Oracle database.

SELECT
*
FROM OPENQUERY([REMOTE_ORACLE_DB], 'SELECT * FROM Player')

We run the SELECT query against the linked Oracle server using the OPENQUERY function. As you can see, the query has been successful and returned the desired output.

SELECT OPENQUERY

Example 2: DELETE

Let’s proceed with deleting data from the table located on the remote linked server. To accomplish this task, we will execute the following query.

DELETE OPENQUERY([REMOTE_ORACLE_DB], 'SELECT sports_id, stype, sname, distance, team_type, gender FROM sports_new')
DELETE OPENQUERY

As you can see, the query has been executed successfully.

Example 3: INSERT

Now, let’s attempt to execute the query to select data from the remote Oracle database and insert it into a table located locally in SQL Server.

INSERT INTO SPORTS_NEW (sports_id, stype, sname, distance, team_type, gender)
   SELECT
	 *
   FROM OPENQUERY([REMOTE_ORACLE_DB], 'SELECT sports_id, stype, sname, distance, team_type, gender FROM sports')
GO

The query retrieves data from the table in the Oracle database and inserts it into a table located in SQL Server.

INSERT OPENQUERY

Example 4: UPDATE

Finally, let’s proceed with the UPDATE statement to modify data in the player_new table located on the remote Oracle server. After running the UPDATE query, we will execute a SELECT statement to verify its success.

UPDATE OPENQUERY([REMOTE_ORACLE_DB], 'SELECT Player_ID, PName FROM player_new WHERE player_id = 1')
SET PName = 'Michael Phelps';
UPDATE OPENQUERY

As you can see, the changes have been applied as intended.

Handling errors in OPENQUERY

To handle errors with OPENQUERY, you can use TRY…CATCH blocks in SQL Server. By wrapping the OPENQUERY call inside a TRY block, you can catch any exceptions that might arise and take appropriate action.

BEGIN TRY
  -- Your OPENQUERY statement here
  -- Example: SELECT * FROM OPENQUERY([RemoteServer], 'SELECT * FROM RemoteTable')
END TRY

For example:

Handling errors in OPENQUERY

Performance considerations

When using OPENQUERY to access remote data sources in SQL Server, there are several performance considerations to keep in mind. Properly optimizing your queries can significantly impact the efficiency and speed of data retrieval and manipulation from the remote server. Here are some performance considerations to take into account:

  1. Remote query performance: The performance of the entire operation is influenced by the performance of the remote query. Ensure that the remote query is optimized by using appropriate indexes, limiting the data returned, and avoiding unnecessary calculations or joins.
  2. Data size: Be mindful of the amount of data you are retrieving from the remote server. Fetching a large dataset across the network can lead to performance bottlenecks and increased network traffic. Only select the columns you need and use filtering to fetch only relevant rows.
  3. Network latency: Network latency between the local and remote servers can impact performance. Minimize the number of round-trips between the servers, and consider using a linked server that is physically closer to reduce latency.
  4. Data types: Be aware of data type conversions between the local and remote servers. Converting data types on-the-fly during queries can add overhead. Try to use compatible data types between the servers to avoid unnecessary conversions.
  5. Query complexity: Keep the complexity of your queries to a minimum. Simple and straightforward queries are generally more efficient than complex ones, especially when dealing with remote data sources.
  6. Filtering and Joins: Use filtering conditions to restrict the data retrieved from the remote server to only what is required. Additionally, minimize the use of joins involving tables from both local and remote servers, as these can result in larger datasets and slower performance.
  7. Indexing: Ensure that both the local and remote tables have appropriate indexes to support the queries. Indexes can significantly improve query performance by speeding up data retrieval.

By taking these performance considerations into account, you can make efficient use of OPENQUERY and ensure that data retrieval and manipulation from remote servers are as fast and effective as possible.

Conclusion

OPENQUERY is a powerful Transact-SQL function that allows seamless access to remote data sources in SQL Server. Its ability to execute pass-through queries against linked servers using OLE DB providers provides a direct and straightforward means to interact with data residing on remote servers. Despite potential challenges such as network latency and administrative overhead in setting up linked servers, OPENQUERY offers significant advantages in terms of query flexibility and leveraging the full potential of the remote server’s query engine.


The dbForge team strives to provide a seamless and efficient experience to its users. The popularity of OPENQUERY is growing increasingly, and to stay in line with the latest trends and meet the evolving needs of SQL Server professionals, Devart has extended support for OPENQUERY syntax across all of its dbForge tools for SQL Server, including the renowned dbForge Studio for SQL Server, which is a comprehensive and universal IDE for SQL Server.

Ready to unlock the latest enhancements? Upgrade your dbForge tools to the recent version now and enjoy all the new features! If you haven’t experienced our tools yet, we invite you to give them a try. All dbForge products for SQL Server – dbForge Studio, SQL Tools, and SQL Complete – come with free trials, allowing you to evaluate their capabilities and see how they can help in your database tasks.

download studio for SQL Server
Helena Alexander
Helena Alexander
dbForge Team
RELATED ARTICLES

Whitepaper

Social

Topics

Products