使用带 where 条件的 bcp 将 SQL 导出到 XML
Export SQL to XML using bcp with where condition
我尝试使用此代码将数据导出到 XML,它通常工作正常:
declare @cmd nvarchar(255);
select @cmd = 'bcp "SELECT * from [db].[dbo].[TW_StockReport](0,25,26,4,29,30,19,31) row For XML auto, XMLSCHEMA, root(''node'')" ' +
'queryout "D:\Temp\dbstockandsalereport.xml" -S -T -w -r -t';
exec xp_cmdshell @cmd;
但是当我尝试添加 WHERE
条件时,它不再起作用:
declare @cmd1 nvarchar(1155);
select @cmd1 = 'bcp "SELECT INVENTLOCATIONID, AgeOfItem AS ''ProductYear'', ISNULL(SUM(Qty), 0) AS ''Unit'', COUNT(c.ItemID) AS ''ProductType''
FROM [db].[dbo].[TW_ItemsNonMovement] c
LEFT JOIN [db].[dbo].[TempInventTable] d ON c.ITEMID = d.ITEMID collate Thai_CI_AS
WHERE d.TW_DEPARTMENTID = ''PMMan'' AND DateDiff <= 120 AND Qty > 0
GROUP BY INVENTLOCATIONID, AgeOfItem ORDER BY INVENTLOCATIONID, AgeOfItem row FOR XML AUTO, XMLSCHEMA, ROOT(''node'') ;"' +
'queryout "D:\Temp\PMMan-120.xml" -S -T -w -r -t';
exec xp_cmdshell @cmd1;
最好创建一个存储过程 (SP) 并将整个 SELECT
语句放在那里。之后只需在 bcp 中调用该存储过程即可。
另外。这样您就可以始终自行测试 SP 并确保它按预期运行。
所以会变成这样:
bcp "EXEC yourStoredProcedure;" ...
我尝试使用此代码将数据导出到 XML,它通常工作正常:
declare @cmd nvarchar(255);
select @cmd = 'bcp "SELECT * from [db].[dbo].[TW_StockReport](0,25,26,4,29,30,19,31) row For XML auto, XMLSCHEMA, root(''node'')" ' +
'queryout "D:\Temp\dbstockandsalereport.xml" -S -T -w -r -t';
exec xp_cmdshell @cmd;
但是当我尝试添加 WHERE
条件时,它不再起作用:
declare @cmd1 nvarchar(1155);
select @cmd1 = 'bcp "SELECT INVENTLOCATIONID, AgeOfItem AS ''ProductYear'', ISNULL(SUM(Qty), 0) AS ''Unit'', COUNT(c.ItemID) AS ''ProductType''
FROM [db].[dbo].[TW_ItemsNonMovement] c
LEFT JOIN [db].[dbo].[TempInventTable] d ON c.ITEMID = d.ITEMID collate Thai_CI_AS
WHERE d.TW_DEPARTMENTID = ''PMMan'' AND DateDiff <= 120 AND Qty > 0
GROUP BY INVENTLOCATIONID, AgeOfItem ORDER BY INVENTLOCATIONID, AgeOfItem row FOR XML AUTO, XMLSCHEMA, ROOT(''node'') ;"' +
'queryout "D:\Temp\PMMan-120.xml" -S -T -w -r -t';
exec xp_cmdshell @cmd1;
最好创建一个存储过程 (SP) 并将整个 SELECT
语句放在那里。之后只需在 bcp 中调用该存储过程即可。
另外。这样您就可以始终自行测试 SP 并确保它按预期运行。
所以会变成这样:
bcp "EXEC yourStoredProcedure;" ...