gpt4 book ai didi

sql - 将传递给 xp_cmdshell 的命令参数转义给 dtexec

转载 作者:行者123 更新时间:2023-12-04 23:46:45 26 4
gpt4 key购买 nike

我正在使用存储过程和对 xp_cmdshell 的调用远程调用 SSIS 包:

declare @cmd varchar(5000)
set @cmd = '"C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\dtexec.exe" /Rep E /Sql Package /SET \Package.Variables[User::ImportFileName].Value;c:\foo.xlsx'
print @cmd
exec xp_cmdshell @cmd

这工作正常,但是我不能保证变量值 (c:\foo.xslx) 不会包含空格,所以我想用下面的引号转义它:
set @cmd = '"C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\dtexec.exe" /Rep E /Sql Package /SET \Package.Variables[User::ImportFileName].Value;"c:\foo.xlsx"'

但是通过这样做我得到了错误
'C:\Program' is not recognized as an internal or external command, operable program or batch file.

如果在 cmd.exe 中执行,上述两个命令都可以正常工作,所以我猜测 SQL Server 正在解释我的双引号并更改某些内容,但我不知道是什么。

最佳答案

简而言之,输入 CMD /S /C "开头,还有"在末尾。在两者之间,您可以有任意多的引号。

这是你如何做到的:

declare @cmd varchar(8000)
-- Note you can use CMD builtins and output redirection etc with this technique,
-- as we are going to pass the whole thing to CMD to execute
set @cmd = 'echo "Test" > "c:\my log directory\logfile.txt" 2> "c:\my other directory\err.log" '


declare @retVal int
declare @output table(
ix int identity primary key,
txt varchar(max)
)


-- Magic goes here:
set @cmd = 'CMD /S /C " ' + @cmd + ' " '

insert into @output(txt)
exec @retVal = xp_cmdshell @cmd
insert @output(txt) select '(Exit Code: ' + cast(@retVal as varchar(10))+')'

select * from @output

关于sql - 将传递给 xp_cmdshell 的命令参数转义给 dtexec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3759331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com