SqlServer调⽤OPENQUERY函数远程执⾏增删改查/*
OPENQUERY函数,远程执⾏数据库增删改查
关于OPENQUERY函数第⼆个参数不⽀持拼接变量的⽅案字符串函数怎么用
⽅案1:将OPENQUERY语句整个拼接为字符串,再⽤EXEC执⾏该字符串语句
⽅案2:将要拼接的变量直接挪移到括号外进⾏拼接
由于字符串中单引号多层引⽤需要⽤到很多个单引号,容易混淆,导致⽅案1写起来头疼、眼睛疼,但是⾃由度⼤,想怎么来就怎么来。
⽽⽅案2能够清晰简洁地使⽤变量,但经我⽬前的测试,发现只有SELECT语句和DELETE语句的WHERE⼦句可以挪移出来(见上⽅SQL语句),限制太⼤。OPENQUERY(MySQL, 'select * from hhp_user where chrusername = ''hhp'';')
第⼀个参数为配置好的链接服务器名称,第⼆个参数为要执⾏的MySQL命令
*/
DECLARE @username NVARCHAR(50),
@pwd VARCHAR(64),
@pwdmd5 VARCHAR(64),
@sql VARCHAR(2000),
@sql2 VARCHAR(2000)
--设置⽤户名
SET @username = 'hhp'
--设置密码
SET @pwd = '123456'
--对密码进⾏MD5加密
SET @pwdmd5 = SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', @pwd)),3,32)
-
-1.SELECT语句
SELECT * FROM OPENQUERY(MySQL, 'select * from hhp_user where chrusername = ''hhp'';');
--或
SELECT * FROM OPENQUERY(MySQL, 'select * from hhp_user') WHERE chrusername = @username
--2.INSERT语句,INTO可省略
INSERT INTO OPENQUERY(MySQL,'select chrusername,chrpwd from hhp_user;') VALUES( @username , @pwdmd5)
--3.UPDATE语句
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语句,FROM可省略
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
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论