SqlServer call OPENQUERY function remotely perform CRUD

/*
OPENQUERY function, perform remote database CRUD
Program on the OPENQUERY function The second argument is not supported by splicing a variable
Scheme 1: The entire splice OPENQUERY statement is a string, then the execution of the EXEC statement string
Scheme 2: variable to be spliced ​​directly to the diversion outside the parentheses splicing
Since the multi-layer reference the string in single quotes need to use a lot of single quotes, confusing, resulting in Scheme 1 to write headache, eye pain, however large degree of freedom, how to on how to think.
The program 2 can be clear and concise to use variables, but by our current test, and found that only the SELECT statement DELETE statement WHERE clause diversion out (see above SQL statement), too restrictive.
OPENQUERY(MySQL, 'select * from hhp_user where chrusername = ''hhp'';')
MySQL command first parameter is configured linked server name, the second parameter is to be executed
*/
 
 
DECLARE @username NVARCHAR(50), 
        @pwd VARCHAR(64), 
        @pwdmd5 VARCHAR(64),
        @sql VARCHAR(2000), 
        SQL2 VARCHAR @ ( 2000 )
 - set the user name
@UserName the SET = ' HHP ' 
- Set Password
@Pwd the SET = ' 123456 ' 
- passwords encrypted MD5
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'';');
--
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 may be omitted
DELETE FROM OPENQUERY(MySQL, 'select * from hhp_user where chrusername = ''hhp''')
--
SET @username = 'ls'
DELETE FROM OPENQUERY(MySQL, 'select * from hhp_user') WHERE chrusername = @username 
 

 

Guess you like

Origin www.cnblogs.com/lgx5/p/11691514.html