(Transfer) SqlServer calls the OPENQUERY function to remotely perform additions, deletions, and changes

Due to business requirements, my SqlServer database is connected to a remote MySQL database through MySQL 's ODBC driver. How to remotely execute MySQL commands on SqlServer? After some Baidu, the exercises are organized as follows

 

 

 

/*  
OPENQUERY function, remote execution of database addition, deletion, modification and query  
About the scheme that the second parameter of the OPENQUERY function does not support splicing variables  
Option 1: Concatenate the entire OPENQUERY statement into a string, and then execute the string statement with EXEC  
Option 2: Move the variables to be spliced ​​directly outside the brackets for splicing  
  
Since multiple single quotation marks are used for multi-layered quotations in the string, it is easy to be confused, which leads to headache and eye pain when writing scheme 1.  
Option 2 can use variables clearly and concisely, but through my current tests, I found that only the WHERE clause of the SELECT statement and the DELETE statement can be moved out (see the SQL statement above), which is too restrictive.  
  
OPENQUERY(MySQL, 'select * from hhp_user where chrusername = ''hhp'';')  
The first parameter is the configured linked server name, and the second parameter is the MySQL command to be executed  
*/  
  
  
DECLARE @username NVARCHAR(50),   
        @pwd VARCHAR(64),   
        @pwdmd5 VARCHAR(64),  
        @sql VARCHAR(2000),   
        @sql2 VARCHAR(2000)  
--set username  
SET @username = 'hhp'  
--set password  
SET @pwd = '123456'  
-- MD5 encryption of the password  
SET @pwdmd5 = SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', @pwd)),3,32)  
  
--1.SELECT statement  
SELECT *  FROM  OPENQUERY(MySQL, 'select * from hhp_user where chrusername = ''hhp'';');  
--or  
SELECT * FROM OPENQUERY(MySQL, 'select * from hhp_user') WHERE chrusername = @username  
  
--2.INSERT statement, INTO can be omitted  
INSERT INTO OPENQUERY(MySQL,'select chrusername,chrpwd from hhp_user;')  VALUES( @username , @pwdmd5)  
  
--3.UPDATE statement  
SET @pwd = 'hhp'  
SET @pwdmd5 = SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', @pwd)),3,32)  
UPDATE OPENQUERY(MySQL, 'select chrusername, chrpwd from hhp_user where chrusername = ''hhp''') SET chrpwd = @pwdmd5  
  
--4.DELETE statement, FROM can be omitted  
DELETE FROM OPENQUERY(MySQL, 'select * from hhp_user where chrusername = ''hhp''')  
--or  
SET @username = 'ls'  
DELETE FROM OPENQUERY(MySQL, 'select * from hhp_user') WHERE chrusername = @username   

 

 

 

REFS:http://blog.csdn.net/u012143455/article/details/49929137

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326358061&siteId=291194637
Recommended