4

我有这个 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

@bcppathC:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe空间的。

如果在 path 周围不使用双引号"",则会出现错误'C:\Program' is not recognized... With using double quotes,它会给出相同的错误。使用双双引号"" "",它说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;

编辑:

奇怪的是,我ECHO ? &&在“路径”前面放了一个,它起作用了(用双引号括起来。)....为什么?

4

4 回答 4

8

你必须在引用路径之前放一些东西以避免错误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
于 2016-01-22T01:49:02.937 回答
5

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

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

于 2011-04-06T16:49:44.987 回答
1

作为解决方法,您可以使用subst.

subst p: "C:\Program Files\Microsoft SQL Server\"

所以你不再需要间隔路径了。

或者你试图找出它失败的原因。

exec xp_cmdshell 'cmd /c echo %cmdcmdline% "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe"'

cmdcmdline 应该向您显示完整的命令,如果引号已经存在,这应该可以工作

exec xp_cmdshell 'cmd /c "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe" <the rest of your command>'
于 2011-04-06T19:16:25.103 回答
0

这种奇怪的结构也有效:

exec xp_cmdshell '""%ProgramFiles%\WinRAR\"rar.exe a -v20M "C:\test\test.rar" "C:\test\data\""'
于 2017-11-14T05:49:54.920 回答