代码之家  ›  专栏  ›  技术社区  ›  amarsuperstar

转义传递给xp\u cmdshell到dtexec的命令参数

  •  3
  • amarsuperstar  · 技术社区  · 16 年前

    我正在使用存储过程和对xp\u 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.
    

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

    2 回复  |  直到 16 年前
        1
  •  8
  •   Ben    13 年前

    简而言之,把 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
    
        2
  •  3
  •   amarsuperstar    16 年前

    要绕过这个限制,可以使用旧的DOS表示法,或者将代码放在批处理文件中,这样可以运行良好。

    资料来源: http://social.msdn.microsoft.com/forums/en-US/sqlintegrationservices/thread/4e7024bb-9362-49ca-99d7-1b74f7178a65

    推荐文章