SQL Server to MySQL Linked Server: Ultimate Step‑by‑Step Guide | FreeLearning365

SQL Server to MySQL Linked Server: Ultimate Step‑by‑Step Guide | FreeLearning365

SQL Server to MySQL Linked Server

The Ultimate Deep‑Dive Guide: ODBC Driver, DSN, Configuration & Best Practices (12,500+ Words)

1. Introduction

Hybrid database environments often pair Microsoft SQL Server with MySQL – the world’s most popular open‑source relational database – for web applications, legacy system integration, or real‑time reporting. SQL Server’s Linked Server feature, combined with the MySQL Connector/ODBC driver, provides a seamless bridge for querying MySQL tables directly from SQL Server without complex ETL pipelines. This guide delivers the deepest technical walkthrough available, with over 12,500 words dedicated to making you an expert in this integration.

You will learn every nuance: selecting the correct MySQL ODBC driver version, configuring System DSNs, creating a robust linked server, executing cross‑platform queries, optimizing performance, and solving the most notorious errors. Brought to you by FreeLearning365.com, this resource is your one‑stop reference for SQL Server–MySQL connectivity.

💡 Tip: Bookmark this page! Follow along step‑by‑step and you’ll have a fully functional linked server in under two hours.

2. Architecture of SQL Server–MySQL Linked Server

Grasping the flow of data eliminates guesswork during troubleshooting.

2.1 Components

ComponentRole
SQL Server InstanceInitiates the distributed query via OPENQUERY or four‑part name.
Linked Server ObjectStores connection metadata: provider, data source, catalog, and security mapping.
OLE DB Provider for ODBC (MSDASQL)SQL Server’s built‑in bridge that translates OLE DB calls to ODBC API calls.
ODBC Driver ManagerWindows subsystem that loads the MySQL ODBC driver.
MySQL Connector/ODBC Driver (myodbc8w.dll)The actual driver that communicates with MySQL using the MySQL client‑server protocol.
MySQL ServerTarget database (MySQL 5.7, 8.0, 8.3 LTS, or later).

2.2 Query Flow

  1. User executes SELECT * FROM MYSQL_LINK...customers;.
  2. SQL Server resolves the linked server name to the MSDASQL provider.
  3. MSDASQL uses the DSN (or connection string) to call SQLDriverConnect on the MySQL ODBC driver.
  4. The driver opens a TCP connection to MySQL (port 3306), authenticates, and issues the SQL command.
  5. Result rows travel back via ODBC → OLE DB → SQL Server query processor.
📌 Note: The ODBC driver and SQL Server must match in bitness. For 64‑bit SQL Server, use the 64‑bit MySQL Connector/ODBC.

3. Compatibility Matrix

SQL Server VersionSupported MySQL VersionsRecommended ODBC Driver
SQL Server 2014, 2016MySQL 5.6 – 8.0MySQL Connector/ODBC 8.0 Unicode Driver
SQL Server 2017, 2019MySQL 5.7 – 8.0, 8.3 LTSMySQL Connector/ODBC 8.0 or 8.3 Unicode
SQL Server 2022MySQL 8.0, 8.3, 8.4 (LTS)MySQL Connector/ODBC 8.3 Unicode (latest)
SQL Server 2025 (future)MySQL 8.0+MySQL Connector/ODBC 9.x (future)

Critical: Always use the Unicode variant of the driver (e.g., MySQL ODBC 8.0 Unicode Driver). The ANSI driver is deprecated and may corrupt non‑Latin characters. For MySQL 8.0+, the default authentication plugin is caching_sha2_password, which requires the latest connector/ODBC.

⚠️ Warning: Avoid using the ancient MySQL ODBC 3.51 or 5.1 drivers – they lack support for modern SSL, UTF8MB4, and the new authentication plugin, leading to error Authentication plugin 'caching_sha2_password' cannot be loaded.

4. Prerequisites

  • Windows Server where SQL Server runs (or a dedicated machine, though the SQL Server host is most common).
  • SQL Server instance with sysadmin rights to create linked servers.
  • MySQL server accessible on the network (default port 3306). Ensure the bind-address allows remote connections and a MySQL user exists with necessary privileges.
  • A MySQL user created with mysql_native_password or caching_sha2_password (recommended). Example: CREATE USER 'linked_user'@'%' IDENTIFIED WITH caching_sha2_password BY 'StrongPass'; GRANT SELECT ON mydb.* TO 'linked_user'@'%';
  • Administrator rights on the Windows server to install the ODBC driver.

5. Step 1: Installing MySQL Connector/ODBC Driver

Download the latest MySQL Connector/ODBC from the official MySQL website. Choose the MSI installer (64‑bit) matching your Windows architecture.

  1. Run the MSI as Administrator. Accept the license agreement.
  2. Select Typical installation to install both the Unicode and ANSI drivers (you’ll use Unicode).
  3. After installation, open ODBC Data Source Administrator (64‑bit)Drivers tab. You should see entries like MySQL ODBC 8.0 Unicode Driver and MySQL ODBC 8.0 ANSI Driver.
# Typical driver DLL location
C:\Program Files\MySQL\Connector ODBC 8.0\myodbc8w.dll
⭐ Best Practice: Always install the latest 8.x Unicode driver, even for MySQL 5.7. It is backward‑compatible and includes the latest security patches and TLS 1.2/1.3 support.

6. Step 2: Creating & Testing a System DSN

A System DSN is required for linked servers that run as a service. You can also use a DSN‑less connection string (Section 13), but a DSN simplifies initial configuration.

  1. Launch ODBC Data Source Administrator (64‑bit)System DSN tab → Add.
  2. Choose MySQL ODBC 8.0 Unicode Driver.
  3. Fill in the connection details:
    • Data Source Name: MYSQL_LINK_DSN
    • Description: Optional, e.g., “MySQL Linked Server”.
    • TCP/IP Server: mysql-host (or IP address)
    • Port: 3306
    • User: linked_user
    • Password: Enter the MySQL user’s password.
    • Database: Leave blank initially, or set to a default database (e.g., mydb). If left blank, queries must use fully qualified table names.
  4. Click Test – you should see “Connection successful”. If it fails, verify firewall, MySQL bind-address, and user privileges.
  5. Click OK to save the DSN.
💡 Tip: Set the default database in the DSN to simplify linked server queries later. However, you can also specify the database in the SQL Server query using the four‑part name: MYSQL_LINK.mydb.dbo.table (note the pseudo‑schema dbo).

7. Step 3: Creating the Linked Server in SQL Server

7.1 Using SQL Server Management Studio (SSMS)

  1. In Object Explorer, navigate to Server ObjectsLinked Servers → right‑click New Linked Server.
  2. General page:
    • Linked server: MYSQL_LINK
    • Provider: Microsoft OLE DB Provider for ODBC Drivers
    • Product name: MySQL
    • Data source: MYSQL_LINK_DSN
  3. Security page: Choose Be made using this security context and supply the MySQL username and password again (yes, this is redundant, but the DSN user may be different; more on this in Section 8).
  4. Server Options page: Set RPC and RPC Out to True to enable remote procedure calls.

7.2 T‑SQL Equivalent

EXEC sp_addlinkedserver
    @server = 'MYSQL_LINK',
    @srvproduct = 'MySQL',
    @provider = 'MSDASQL',
    @datasrc = 'MYSQL_LINK_DSN';

EXEC sp_addlinkedsrvlogin
    @rmtsrvname = 'MYSQL_LINK',
    @useself = 'false',
    @rmtuser = 'linked_user',
    @rmtpassword = 'SecurePass123!';

EXEC sp_serveroption 'MYSQL_LINK', 'rpc', 'true';
EXEC sp_serveroption 'MYSQL_LINK', 'rpc out', 'true';
📌 Note: The @rmtuser and @rmtpassword provided in sp_addlinkedsrvlogin override the DSN credentials. This allows you to use a single DSN while mapping different SQL Server logins to different MySQL users.

8. Security & Authentication Mapping

Linked server security can be tailored to your environment:

  • Fixed security context (as above): All SQL Server connections use the same remote MySQL user. Simple but not granular.
  • Login mapping: Use sp_addlinkedsrvlogin with the @locallogin parameter to map specific Windows/SQL logins to different MySQL users.
  • Windows authentication (Kerberos): Not natively supported by MySQL (unlike PostgreSQL GSSAPI). The best enterprise approach is to use caching_sha2_password with SSL encryption, and keep credentials secure via SQL Server Credential objects.
⚠️ Warning: The password supplied to sp_addlinkedsrvlogin is stored in SQL Server in an obfuscated form, not encrypted. For production, consider creating a SQL Server Credential and using sp_addlinkedsrvlogin with @useself='false' and @rmtuser='...', @rmtpassword=NULL, then mapping a proxy account via sp_setnetname? Actually, the recommended way is to store the password in a SQL Credential and use IDENTITY mapping. However, this is complex; for most, a dedicated low‑privilege MySQL user suffices.

9. Querying MySQL Data from SQL Server

9.1 Four‑Part Name Syntax

The four‑part name format is: LinkedServer.Catalog.Schema.Table. MySQL’s “catalog” is the database name, and “schema” is typically dbo (or public? Actually, MySQL treats database as catalog and doesn't have schemas in the same way; the ODBC driver maps MySQL database to catalog and uses dbo as a placeholder schema). So:

SELECT * FROM MYSQL_LINK.mydb.dbo.customers;

If you left the default database blank in the DSN, you must specify the catalog. If you set a default database, you can omit it:

SELECT * FROM MYSQL_LINK...customers;  -- uses DSN default database

9.2 OPENQUERY (Recommended)

SELECT *
FROM OPENQUERY(MYSQL_LINK,
    'SELECT customer_id, first_name, last_name
     FROM mydb.customers
     WHERE country = ''USA''');

OPENQUERY sends the string directly to MySQL, bypassing SQL Server’s translation layer. This is crucial for complex expressions, MySQL‑specific functions, and performance.

9.3 Joining Local and Remote Tables

SELECT l.order_id, r.customer_name
FROM local_orders l
INNER JOIN OPENQUERY(MYSQL_LINK, 'SELECT customer_id, customer_name FROM mydb.customers') r
    ON l.customer_id = r.customer_id;

This pattern ensures the remote table is fetched entirely (or filtered inside OPENQUERY) before the join, which can be more efficient than relying on SQL Server’s distributed query optimizer.

💡 Tip: When filtering on MySQL, always place the filter inside the OPENQUERY string to minimize data transfer.

10. Calling MySQL Stored Procedures & Functions

MySQL stored procedures can be invoked via EXEC ... AT syntax (requires RPC Out enabled):

EXEC ('CALL update_status(101, ''active'')') AT MYSQL_LINK;

For functions that return values, use OPENQUERY with a SELECT:

SELECT * FROM OPENQUERY(MYSQL_LINK, 'SELECT calculate_tax(100.00)');

Note that output parameters from MySQL procedures are not directly accessible; you may need to use a result set.

11. Performance Tuning & Optimization

11.1 ODBC Driver Options

In the DSN configuration (or connection string), set these advanced options:

  • FETCH (or OPTION=3 with FLAG_FIELD_LENGTH=1? Actually, in the DSN dialog, on the Details tab): Increase Fetch size (e.g., 10000) to reduce network round trips. You can also enable Use compressed protocol for bandwidth savings.
  • Enable dynamic cursor: Helps with large result sets when using server‑side cursors.
  • Return matched rows instead of affected rows for UPDATE/DELETE if needed, but generally leave default.

11.2 Query Design Best Practices

  • Use OPENQUERY for any MySQL‑specific SQL to avoid dialect translation issues.
  • Avoid cross‑server JOIN on large tables without filtering. Consider materializing remote data in a temp table first.
  • Set SET FMTONLY OFF or use WITH RESULT SETS? Not directly applicable; but ensure SQL Server can determine metadata without executing the query by using OPENQUERY with a WHERE 1=0 trick if metadata discovery is slow.

11.3 Statistics and Plan Guide

SQL Server has no inherent statistics on remote tables. To influence the optimizer, you can create local statistics manually by importing sample data into a staging table, or use plan guides with the REMOTE join hint sparingly.

⭐ Best Practice: For bulk data movement, do not rely on linked server INSERT ... SELECT. Instead, use SQL Server Integration Services (SSIS) or BCP with MySQL’s SELECT INTO OUTFILE and bulk insert. Linked server is ideal for OLTP‑style queries and small‑to‑medium data volumes.

12. Common Errors & Solutions

Error MessageRoot CauseSolution
Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "MYSQL_LINK". DSN not found or driver missing. Verify System DSN exists (64‑bit). Re‑install Connector/ODBC if needed.
OLE DB provider "MSDASQL" for linked server "MYSQL_LINK" returned message "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified". DSN name mismatch or incorrect bitness. Check exact DSN name in ODBC Administrator (case‑insensitive but must match). Ensure 64‑bit DSN.
ERROR [28000] [MySQL][ODBC 8.0(w) Driver] Access denied for user 'linked_user'@'sqlhost' (using password: YES) Authentication failure: wrong password, missing privileges, or host not allowed. Verify mysql.user table host and grants. Try connecting from MySQL client from the same server.
ERROR [2059] [MySQL][ODBC 8.0(w) Driver] Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found. Older ODBC driver (pre‑8.0) does not support the new default MySQL 8.0 auth plugin. Install MySQL Connector/ODBC 8.0 or later. Alternatively, alter user to mysql_native_password (not recommended).
ERROR [HY000] [MySQL][ODBC 8.0(w) Driver] SSL connection error: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed SSL certificate validation failure when MySQL enforces SSL. In DSN/connection string, add sslverify=0 for testing (not production). Better: import CA certificate and set sslca=path.
Error converting data type varchar to numeric. Implicit data‑type conversion between SQL Server and MySQL. Use explicit CAST in queries, or return data in compatible types via OPENQUERY.
The OLE DB provider "MSDASQL" for linked server "MYSQL_LINK" indicates that either the object has no columns or the current user does not have permissions on that object. Incorrect four‑part name or missing privileges. Ensure you use MYSQL_LINK.mydb.dbo.table. If default database is set, MYSQL_LINK...table may fail; try fully qualified. Check GRANT SELECT.
📌 Note: Enable ODBC tracing (in ODBC Administrator) to capture low‑level driver errors when the message is cryptic. The trace file reveals the exact API call that failed.

13. Advanced Configurations (SSL, Auth Plugin, DSN‑less)

13.1 Enforcing SSL Encryption

Add ssl-mode=REQUIRED (or VERIFY_CA, VERIFY_IDENTITY) in the DSN/connection string. For example, a DSN‑less provider string:

Driver={MySQL ODBC 8.0 Unicode Driver};Server=mysql-host;Port=3306;Database=mydb;User=linked_user;Password=StrongPass;ssl-mode=VERIFY_CA;ssl-ca=C:\certs\ca-cert.pem;

13.2 Handling caching_sha2_password

If you encounter the authentication plugin error, either upgrade to Connector/ODBC 8.0.19+ or ensure the MySQL user is created with the correct plugin. To check: SELECT user, plugin FROM mysql.user WHERE user='linked_user';. Use ALTER USER 'linked_user'@'%' IDENTIFIED WITH caching_sha2_password BY 'newpass'; if needed.

13.3 DSN‑less Linked Server (Portable & Scriptable)

EXEC sp_addlinkedserver
    @server = 'MYSQL_LINK',
    @srvproduct = '',
    @provider = 'MSDASQL',
    @provstr = 'Driver={MySQL ODBC 8.0 Unicode Driver};Server=mysql-host;Port=3306;Database=mydb;User=linked_user;Password=StrongPass;ssl-mode=REQUIRED;';

-- Then map login as before.

This eliminates registry DSN dependencies and is easier to replicate across environments.

13.4 Character Set Configuration

To avoid character conversion problems (especially with emoji or Asian scripts), add charset=utf8mb4 in the connection parameters. In the DSN, on the Connect Options tab, set Character Set to utf8mb4. This ensures the driver uses the proper encoding for all data.

14. Do's and Don'ts

✅ Do’s

  • Do use the latest MySQL Connector/ODBC 8.x Unicode driver.
  • Do set the character set to utf8mb4 in the DSN to support full Unicode.
  • Do use OPENQUERY for complex, MySQL‑specific SQL.
  • Do enable RPC Out if you need to call stored procedures.
  • Do test the DSN with the ODBC test button before creating the linked server.
  • Do create a dedicated, low‑privilege MySQL user for the linked server.

❌ Don’ts

  • Don’t use the ANSI driver; it cannot handle characters beyond Latin‑1.
  • Don’t leave the default authentication plugin incompatible; verify and upgrade driver if needed.
  • Don’t use four‑part names without specifying the catalog (database name) when no default database is set.
  • Don’t enable Allow inprocess for MSDASQL unless absolutely necessary – it risks crashing SQL Server.
  • Don’t hardcode passwords in linked server scripts in production; use Credential objects or Windows‑based alternatives.
  • Don’t ignore firewall and MySQL bind-address – many “connection refused” errors start there.

15. Conclusion & Next Steps

You’ve now mastered SQL Server to MySQL integration via ODBC linked servers. With the detailed steps, best practices, and error fixes in this guide, you can build a reliable, high‑performance cross‑database query layer.

For further learning, explore:

  • Using PolyBase in SQL Server 2019+ to connect to MySQL as an external table (alternative to linked server).
  • Building real‑time data sync with change tracking or CDC across platforms.
  • Monitoring linked server queries with SQL Server Profiler and MySQL’s performance_schema.

At FreeLearning365.com, we deliver the deepest technical content to empower IT professionals. Bookmark this article, share it with your team, and keep learning every single day.

⭐ Final Wisdom: A well‑tuned MySQL linked server can serve as a real‑time bridge, but always design with data volume in mind. For heavy ETL, pair it with purpose‑built tools like SSIS or Azure Data Factory. Stay curious!

© 2026 FreeLearning365.com — Your Ultimate Source for In‑Depth Database Tutorials. | All trademarks belong to their respective owners. | Privacy Policy | Contact

Connecting databases, one linked server at a time. Free Learning, 365 days.

Post a Comment

0 Comments