通过bcp结合大量SQL查询和查询

时间:2017-04-10 13:42:50

标签: sql sql-server

我尝试将超过60个SQL查询合并到一个查询中,并通过BCP将结果导出到一个.CSV个文件。

我设法将它们与UNION ALL组合并运行1个BCP命令,该命令适用于2个查询,但不包含> 40: - )

我收到错误:

  

查询提示超过最大命令缓冲区大小8191字节(输入24324字节)

查询几乎完全相同,每次只有Location的结尾不同。

SELECT 
    ISNULL(REPLACE(LEFT(SUM([Sales Amount (Actual)]) * 1.21, LEN(SUM([Sales Amount (Actual)])) -18 ),'.', ','),0) Result 
FROM 
    _DBHERE_ 
WHERE 
    ([Item] = 1) 
    AND ([Date] = CAST(GETDATE() AS DATE)) 
    AND ([Location] = '1')

SELECT 
    ISNULL(REPLACE(LEFT(SUM([Sales Amount (Actual)]) * 1.21, LEN(SUM([Sales Amount (Actual)])) -18 ),'.', ','),0) Result 
FROM 
    _DBHERE_ 
WHERE 
    ([Item] = 1) 
    AND ([Date] = CAST(GETDATE() AS DATE)) 
    AND ([Location] = '2')

1 个答案:

答案 0 :(得分:1)

试试这个

 SELECT 
[Location]
, ISNULL(REPLACE(LEFT(SUM([Sales Amount (Actual)]) * 1.21, LEN(SUM([Sales 
  Amount (Actual)])) -18 ),'.', ','),0) Result 
 FROM 
    _DBHERE_ 
 WHERE [Item] = 1
 AND [Date] = CAST(GETDATE() AS DATE) 
 AND [Location] IN ('1', '2', ......) -- replace ... with comma separated list of required values
 GROUP BY [Location]
 ;

你只需要"和[位置] IN"如果您限制[位置]值,则行。如果您想要所有位置,则不需要此行。或者作为评论,您可以加入位置表并使用您拥有的任何标准来限制位置

根据OP的评论更新 假设你有一个[位置]表,你可以这样做:

SELECT 
L.[Location]
, ISNULL(REPLACE(LEFT(SUM(S.[Sales Amount (Actual)]) * 1.21, LEN(SUM(S.[Sales 
  Amount (Actual)])) -18 ),'.', ','),0) Result 
 FROM [Location] L
 LEFT OUTER JOIN [SalesData] S
 ON S.[Location] = L.[Location]
 AND S.[Item] = 1
 AND S.[Date] = CAST(GETDATE() AS DATE) 
 WHERE L.[Location] IN ('1', '2', ......) -- replace ... with comma separated list of required values
 GROUP BY L.[Location]
 ;