带有 WHERE 子句的 BCP 失败

BCP with WHERE clause Fails

当使用 BCP 将数据从 table 导出到 XML 文件时,这非常有效:

declare @cmd nvarchar(255);
select @cmd = '
    bcp "select AGENT,TERMCD ,MYAMOUNT,CAMPNAME,LCDATE,CAMPAIGNID from [MYDATABASE].[dbo].[CC1] row for xml auto, root(''rows''), elements" '
    + 'queryout "d:\temp\sample.xml" -S DESKTOP-2C2OAE9 -T -w -r -t';
exec xp_cmdshell @cmd;
go

但是,如果我像下面这样添加一个简单的 WHERE 子句,它就会失败。

declare @cmd nvarchar(255);
select @cmd = '
    bcp "select AGENT,TERMCD ,MYAMOUNT,CAMPNAME,LCDATE,CAMPAIGNID from [MYDATABASE].[dbo].[CC1] WHERE AGENT=''Kelly Martens'' row for xml auto, root(''rows''), elements" '
    + 'queryout "d:\temp\sample.xml" -S DESKTOP-2C2OAE9 -T -w -r -t';
exec xp_cmdshell @cmd;
go

存在错误:

NULL
Starting copy...
SQLState = 37000, NativeError = 102
Error = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'row'.
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to resolve column level collations
NULL
BCP copy out failed
NULL

我实际上将不得不使用 LCDATE,它是 varchar 来与当前日期进行比较,但我最初想做一些简单的事情,因为我遇到了问题,但如果你也有这样的想法,它会不客气。

您的 'row' table 别名移动到 where 之后,它应该在 table 名字之后

declare @cmd nvarchar(255);
select @cmd = '
    bcp "select AGENT,TERMCD ,MYAMOUNT,CAMPNAME,LCDATE,CAMPAIGNID from [MYDATABASE].[dbo].[CC1] row WHERE AGENT=''Kelly Martens'' for xml auto, root(''rows''), elements" '
    + 'queryout "d:\temp\sample.xml" -S DESKTOP-2C2OAE9 -T -w -r -t';
exec xp_cmdshell @cmd;
go