Microsoft SQL xp_cmdshell不喜欢带空格的文件名.我可以用其他东西替换空间吗?

Zac*_*ott 3 t-sql sql-server-2005 batch-file xp-cmdshell

我有这个TSQL代码使用BCP从表中转储数据.它看起来很复杂,但它只是创建一个@command字符串,为每个表执行一次,然后BCP将表记录转储到磁盘.这是一种快速备份所有表数据的好方法.下面我展示了一个更容易阅读的解析版本.

set @command = 
  'if (''?'' <> ''[dbo].[sysdiagrams]'') 
   BEGIN;
       create table #result (result nvarchar(2048) null );
       declare @temp nvarchar(1000); 
       set @temp = ''' +  @bcpPath + ' ' + @database + '.dbo.'' + 
           substring( ''?'', 8, len(''?'')- 8) +
           '' out "' + @driveLetter + @drivePath +
           '\'' + substring( ''?'', 8, len(''?'')- 8) + 
           ''.out" -c -x -t"|" -Uuser -Ppassword'';
       insert into #result (result)
       exec xp_cmdshell @temp;
       drop table #result;
   END;'
   exec sp_msforeachtable @command
Run Code Online (Sandbox Code Playgroud)

@bcppathC:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe其中有一个空间.

如果不在路径周围使用双引号"",则会出现'C:\Program' is not recognized... 使用双引号的错误,它会产生相同的错误."" ""它说,使用双引号The filename, directory name, or volume label syntax is incorrect.

@command在打印时解析为:

if ('?' <> '[dbo].[sysdiagrams]') 
BEGIN;
    create table #result (result nvarchar(2048) null );
    declare @temp nvarchar(1000); 
    set @temp = '"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe" 
        myDB.dbo.' + 
        substring( '?', 8, len('?')- 8) +
        ' out "E:\DataExports\' + 
        substring( '?', 8, len('?')- 8) + '.out" -c -x -t"|" -Uuser -Ppassword';
    insert into #result (result)
    exec xp_cmdshell @temp;
    drop table #result;
END;
Run Code Online (Sandbox Code Playgroud)

编辑:

奇怪的是,我把它ECHO ? &&放在了"路径"的前面并且它起了作用(用双引号括起来.)....为什么?

hog*_*gar 7

您必须在引用路径之前放置一些东西以避免错误,C:\Program' is not recognized...所以我使用了CALL语句,它对我有用...

declare @cmd nvarchar(1000)

set @cmd = 'call "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe" myDB.dbo.'
exec xp_cmdshell @cmd
Run Code Online (Sandbox Code Playgroud)


arc*_*ain 5

尝试为包含空格的路径部分指定短名称例如,PROGRA~1而不是Program Files.所以,你的第一条路径就像是C:\ PROGRA~1\MI6841~1\90\Tools\Binn\bcp.exe.如果您没有任何空格,您应该可以删除引号.

如果dir /x在包含长目录/文件名的目录中执行a ,则可以获得短8.3名称.