环境:sql server 2008
一、创建网络驱动器映射
语法:exec master..xp_cmdshell 'net use Z: \ip地址网络路径 密码 /user:用户名'
例如:
exec master..xp_cmdshell 'net use Z: \10.216.77.154Data admin /user:admin'
执行结果1:
执行结果2:
遇到此问题请执行:
sp_configure 'show advanced options',1
reconfigure
go
sp_configure 'xp_cmdshell',1
reconfigure
Go
验证是否创建成功:
exec master..xp_cmdshell 'dir Z:'
二、在sql server 中创建txt文件到网络驱动器:
DECLARE @filePath varchar(500)= 'Z:Data',
@strPath varchar(500)= 'Z:Data est.txt'
exec ('sp_configure ''show advanced options'', 1');
exec ('RECONFIGURE');
exec ('sp_configure ''Ole Automation Procedures'', 1');
exec ('RECONFIGURE');
--創建Scripting組件實例
EXEC @hr = sp_OACreate 'Scripting.FileSystemObject', @object OUT
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object, @src OUT, @desc OUT
SELECT hr=convert(varbinary(4),@hr), Source=@src, Description=@desc
RETURN
END
--文件夹是否存在
EXEC @hr = sp_OAMethod @object, 'FolderExists', @tmp OUTPUT, @filePath
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END
else
begin
if(@tmp=0)--不存在创建文件夹
begin
EXEC @hr = sp_OAMethod @object, 'CreateFolder',null, @filePath
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END
end
end
--創建文件
EXEC @hr = sp_OAMethod @object, 'CreateTextFile', @tmp OUTPUT , @strPath
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END
DECLARE @bsl varchar(100)
--写入行数据
EXEC @hr = sp_OAMethod @tmp, 'WriteLine',null, '写入的行数据'
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END
--關閉文件
EXEC @hr = sp_OAMethod @tmp, 'Close',NULL
IF @hr <> 0
BEGIN
EXEC sp_OAGetErrorInfo @object
RETURN
END
end
exec ('sp_configure ''Ole Automation Procedures'', 0');
exec ('RECONFIGURE');
exec ('sp_configure ''show advanced options'', 0');
exec ('RECONFIGURE');