sql-server - 使用变量在批处理文件中调用 sqlcmd.exe 会导致错误 : "unexpected argument"

标签 sql-server windows batch-file cmd sqlcmd

在 Windows 批处理文件中,这有效:

sqlcmd.exe -b -S xxMySqlServerNamexx -Q "BACKUP DATABASE xxMyDatabaseNamexx TO DISK='d:\data\xxMyDatabaseNamexx.bak' with init, compression"  

就像这样:

set vSource_SqlServer="xxMySqlServerNamexx"      
sqlcmd.exe -b -S %vSource_SqlServer% -Q "BACKUP DATABASE xxMyDatabaseNamexx TO DISK='d:\data\xxMyDatabaseNamexx.bak' with init, compression"  

但是这个:

set vSource_SqlServer="xxMySqlServerNamexx"  
set vSource_SqlDbName="xxMyDatabaseNamexx"  
sqlcmd.exe -b -S %vSource_SqlServer% -Q "BACKUP DATABASE %vSource_SqlDbName% TO DISK='d:\data\xxMyDatabaseNamexx.bak' with init, compression"  

...导致错误:

Sqlcmd: 'xxMyDatabaseNamexx" TO DISK='d:\data\xxMyDatabaseNamexx.bak' with init, compression"': Unexpected argument. Enter '-?' for help.

如您所见,它正在使用变量 %vSource_SqlDbName% 代替 xxMyDatabaseNamexx

以这种形式是否有正确的方法来做到这一点(我的意思是,是的,我可能应该使用 Powershell 或替代方法,但我有几个这种形式的现有批处理文件我更愿意转换为使用这种形式的变量,即使这不是最好的方法)?

最佳答案

set 语句不引用其参数。 所以 set a=b c 意味着 %a% 扩展为 b c,而 set a="b c" 意味着它扩展为 "b c ".

因此,在您的非工作示例中,您将双引号文本放在双引号字符串中,这是行不通的。

set 中删除引号,它应该可以工作。

关于sql-server - 使用变量在批处理文件中调用 sqlcmd.exe 会导致错误 : "unexpected argument",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36901011/

相关文章:

Windows 批量自动应答 XCOPY/i

java - 是否可以使用 sql server 2000 和 java 1.4 将 arraylist 对象传递给 sql 过程?

SQL - 即使出现错误也继续运行所有 SQL 语句

windows - Windows 7 RC 中的 "This program might not have installed correctly"消息

适用于 XP 的 Windows 防火墙规则

windows - 让 .bat 在执行期间显示信息(WinSCP)

mysql - 存储过程比简单查询更快/更好吗?

java - SQL Server JDBC 驱动程序无法快速检测丢失的连接

powershell - 如何将文件从旧的文件夹结构移到新的文件夹结构?

string - 批处理文件 : How to get variable's value using variable's name already stored in a string