找回密码
 注册

QQ登录

只需一步,快速开始

查看: 1908|回复: 1

Setup SQL Server Linked Server to MySQL

[复制链接]
发表于 2011-6-7 00:18:05 | 显示全部楼层 |阅读模式
Despite being completely proprietary, one of the nice connectivity features offered in SQL Server is the ability to query other servers through a Linked Server. Essentially, a linked server is a method of directly querying another RDBMS; this often happens through the use of an ODBC driver installed on the server. Fortunately, many popular databases provide this ODBC driver, giving SQL Server the ability to connect to a wide range of other systems. I’ve already written about how to connect Oracle and SQL Server. In this post, I’m going to go through the steps necessary to connect SQL Server and MySQL.


The first step is to fetch an appropriate MySQL Connector/ODBC 5.1 download. Drivers are available for a variety of OS‘s, but we’re obviously focused on Windows or Window x64, which should correspond to the version of SQL Server installed. After you’ve downloaded and installed the driver, we have a few things to configure, so let’s get started:
Configure a MySQL DSNThe first step is to configure a MySQL data source by running the ODBC Data Source Administrator. This step is technically entirely optional, but allows a simpler configuration in the SQL Server Linked Server settings. Instead of composing a complicated MySQL connection string, we can use a simple GUI application.
Run odbcad32

If you’re using Windows Server 2003, bring up a Run dialog box with Start→Run or WinKey+R. If you’re using Windows Server 2008, use the Start Menu search box directly. In either OS, type in “odbcad32″ and hit Enter.
System DSN

Select the System DSN tab to configure a data source for the entire system. If you only want to create the DSN for a specific user (such as your service account), use the User DSN tab. In either scenario, select the “Add…” button.
Create New Data Source

Scroll down in the Create New Data Source window and select “MySQL ODBC 3.51 Driver” and click “Finish”.
MySQL Connector Login Settings

Once added, clicking the “Configure…” button will bring up the Connector/ODBC 3.51 Configure Data Source application. This is where you can specify all the connection settings for connecting SQL Server to MySQL. Select a Data Source Name – I typically name it after the application or database I’m connecting to. The Server, User, Password, and Database should all be obvious.
Test ODBC Connection

After you’ve entered all the required parameters, click the “Test” button to ensure a connection can be made to the MySQL server.
These settings are the bare minimum required to connect MySQL and SQL Server via a linked server, but I like to specify additional options to optimize the connection between the servers. Without these, I have run into “Out of Memory” errors that require restarting the service.
MySQL Connector Advanced Flags 1 Settings

Select the Advanced tab and you’ll be placed on the “Flags 1″ sub-tab. Check the boxes labeled “Allow Big Results” and “Use Compressed Protocol”.
MySQL Connector Advanced Flags 2 Settings

Next, switch to the “Flags 2″ tab and select “Don’t Cache Result (forward only cursors)”. This can actually be a performance penalty if you perform the same query multiple times to the same linked server. However, in my experience, the reason to connect SQL Server to MySQL, is to pull data into a single server, in which case, this option is perfectly suited.
MySQL Connector Advanced Flags 3 Settings

On the “Flags 3″ tab, select “Force Use Of Forward Only Cursors”. When you’re done setting all these options, select the “Ok” button.
Configure Linked Server ProviderAdjusting the Linked Server Provider is simple, but it comes with a caveat: When adjusting a provider, you are adjusting it for all connections using that provider. I am not aware of any way to change these settings on a per-connection basis.
Provider Properties

Drill down to Server Object → Linked Servers → Providers, right-click MSDASQL, and select “Properties”.
Set Provider Options

The Provider Options for Microsoft OLE DB Provider for ODBC Drivers dialog box will open allowing you to configure several options. Ensure the following four options are checked:
  • Nested queries
  • Level zero only
  • Allow inprocess
  • Supports ‘Like’ Operator
All other options should be unchecked. When done, click “OK”.
Create Linked Server to MySQLFinally, the last step in our process is to create the actual MySQL Linked Server.
Create a New Linked Server

You should already have Linked Servers expanded in the Object Explorer tree. If not, find it in Server Objects → Linked Server. Once there, right-click Linked Servers and select “New Linked Server…”
New linked Server Settings

The New Linked Server dialog box will open. Because we specified all our connection settings in the ODBC Data Source Administrator, this last step is very simple. Name the linked server. As with the Data Source Name, I like to name it after the product or database I’m connecting to. In my example, I used MYSQLAPP. Ensure that the “Other data source” option is selected and choose “Microsoft OLE DB Provider for ODBC Drivers” from the Provider dropdown. Lastly, specify the Product name and Data source. The Product name doesn’t matter so much as the Data source must match what you provided in the MySQL Connector/ODBC configuration. Press “OK” when complete.
Testing the SQL Server to MySQL connectionIf everything has been set correctly, you should be able to execute a query directly again the MySQL database from SQL Server Management Studio. For example:
SELECT TOP 10 TABLE_NAME FROM MYSQLAPP...tables WHERE TABLE_TYPE != 'MEMORY'

If you’ve done everything correctly, you should get back a result set. There are several error message you might receive:
OLE DB provider "MSDASQL" for linked server "MYSQLAPP" returned message "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified".Msg 7303, Level 16, State 1, Line 1Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "MYSQLAPP".

The message indicates that the Data source name you’ve specified for the linked server does not match that of the Data Source Name specified in the MySQL Connector.
Msg 7313, Level 16, State 1, Line 1An invalid schema or catalog was specified for the provider "MSDASQL" for linked server "MySQLApp".

This uninsightful error is a result of not correctly setting the options for the Linked Server Provider.
Msg 7399, Level 16, State 1, Line 1The OLE DB provider "MSDASQL" for linked server "MySQLApp" reported an error. The provider did not give any information about the error.Msg 7312, Level 16, State 1, Line 1Invalid use of schema or catalog for OLE DB provider "MSDASQL" for linked server "MySQLApp". A four-part name was supplied, but the provider does not expose the necessary interfaces to use a catalog or schema.

This “four-part name” error is due to a limitation in the MySQL ODBC driver. You cannot switch catalogs/schemas using dotted notation. Instead, you will have to register another DSN and Linked Server for the different catalogs you want to access. Be sure and follow the three-dot notation noted in the example query.
If, however, you want to access other schemas, you can do so utilizing OPENQUERY. This is also a great way to test your connection if you’re receiving problems. The syntax looks like this:
SELECT * FROM OPENQUERY(MYSQLAPP, 'SELECT * FROM INFORMATION_SCHEMA.TABLES LIMIT 10')

Notice that the actual query syntax in the string must be in the MySQL format (SQL Server does not support the LIMIT keyword). Additionally, you can specify a different schema using SCHEMA.TABLENAME in the query.
ConclusionCreating a linked server between SQL Server and MySQL is a simple process. The first time requires you to install the software and configure the Linked Server Provider, but all subsequent connections require only a DSN and Linked Server.
 楼主| 发表于 2011-6-7 00:37:25 | 显示全部楼层
It took me about a day to figure this out, so I thought I'd try to save someone else the pain...

Creating a Linked Server in SSMS for a MySQL database

1. Download the MySQL ODBC driver from mysql.com
2. Install MySQL ODBC driver on Server where SQL Server resides
        -Double Click Windows Installer file and follow directions.

3. Create a DSN using the MySQL ODBC driver
Start-> Settings -> Control Panel -> Administrative Tools -> Data Sources (ODBC)
        -Click on the System DSN tab
        -Click Add
        -Select the MySQL ODBC Driver
        -Click Finish
On the Login Tab:
        -Type a descriptive name for your DSN.
        -Type the server name or IP Address into the Server text box.
        -Type the username needed to connect to the MySQL database into the user text box.
        -Type the password needed to connect to the MySQL database into the password text box.
        -Select the database you'd like to start in.
On the Advance Tab:
Under Flags 1:
        -Check Don't Optimize column width.
        -Check Return Matching Rows
        -Check Allow Big Results
        -Check Use Compressed protocol
        -Check BIGINT columns to INT
        -Check Safe
Under Flags 2:
        -Check Don't Prompt Upon Connect
        -Check Ignore # in Table Name
Under Flags 3:
        -Check Return Table Names for SQLDescribeCol
        -Check Disable Transactions
Now Test your DSN by Clicking the Test button


4. Create a Linked Server in SSMS for the MySQL database
SSMS (SQL Server Management Studio -> Expand Server Objects
        -Right Click Linked Servers -> Select New Linked Server
On the General Page:
        -Linked Server: Type the Name for your Linked Server
        -Server Type: Select Other Data Source
        -Provider: Select Microsoft OLE DB Provider for ODBC Drivers
        -Product name: Type MySQLDatabase
        -Data Source: Type the name of the DSN you created
On The Security Page
        -Map a login to the Remote User and provide the Remote Users Password
        -Click Add under Local server login to remote server login mappings:
        -Select a Local Login From the drop down box
        -Type the name of the Remote User
        -Type the password for the Remote User

5. Change the Properties of the Provider MSDASQL
Expand Providers -> Right Click MSDASQL -> Select Properties
        -Enable Nested queries
        -Enable Level zero only (this one's the kicker)
        -Enable Allow inprocess
        -Enable Supports 'Like' operator

6. Change settings in SQL Server Surface Area Configuration for Features
        -Enable OPENROWSET and OPENDATASOURCE support.
7. Change settings in SQL Server Surface Area Configuration for Services and Connections
        -Enable Local and Remote connections via TCP/IP and named pipes

8. Stop SQL Server and SQL Server Agent
9. Start SQL Server and SQL Server Agent


[url=]Jim Dillon-291542

These instructions for creating a linked MySQL server were great!

I have a couple more questions concerning querying the MySQL tables. I am wondering if I have to use the OpenQuery function in order to query the MySQL database. The OpenQuery function does not allow variables to be used in its arguments and what I need to do is write a stored procedure that calls the MySQL database and gets the data for a certain record or records and inserts it into the SQL Server database tables. I have found that I can create a view of the whole MySQL table in SQL Server and then use the view in the stored procedures to insert into the SQL Server tables, but I'm wondering if that is my only option. I also tried writing a query to select using the four part identifier, but that is not working either. It's probably because there is no owner for the MySQL tables, but I'm really just guessing on that one.

I appreciate any help you can provide.

Thanks!


I figured out how to do this using variables. I used the sp_executesql and was able to return the new identity so that I can use it throughout my stored procedure.

DECLARE @SQLStatement nvarchar(max)
DECLARE @ID as nvarchar(200)
DECLARE @NewID as int
SET @ID = 10

SET @SQLStatement = 'INSERT INTO SQLServerTableName(Col1, Col2, Col3, Col4, Col5)
SELECT * FROM OPENQUERY(LinkedServerName, ''SELECT Col1, Col2, Col3, Col4, Col5 FROM MySQLTableName WHERE ID = ' + Cast(@ID as varchar)+''' ) '

SET @SQLStatement = @SQLStatement + ' SELECT @NewID = SCOPE_IDENTITY()'
EXECUTE sp_executesql @SQLStatement, N'@NewID INTEGER OUT', @NewID OUT


[/url][url=]huskerwendy[/url]
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )

GMT-8, 2026-4-9 23:27 , Processed in 0.033301 second(s), 16 queries .

Supported by Weloment Group X3.5

© 2008-2026 Best Deal Online

快速回复 返回顶部 返回列表