将每个客户的订单导出为单独的CSV文件

时间:2017-09-13 06:02:22

标签: sql sql-server-2012 export-to-csv

我有以下查询:

Select CustomerID, OrderName, OrderQuantity 
from Customers C join Orders O on C.CustomerID = O.CustomerID

结果:

CutomerID | OrderName | OrderQuantity
1001      | Chicken   | 2
1001      | Meat      | 5
1002      | Pepsi     | 13
1002      | 7Up       | 7

是否有将每个客户行导出为单独的CSV文件?

所以customer1001.csv文件将

CutomerID | OrderName | OrderQuantity
1001      | Chicken   | 2
1001      | Meat      | 5

customer1002.csv文件将有

CutomerID | OrderName | OrderQuantity
1002      | Pepsi     | 13
1002      | 7Up       | 7

1 个答案:

答案 0 :(得分:2)

你可以尝试一下吗?您应该在查询中更改数据库名称。

DECLARE CURS CURSOR FOR
Select C.CustomerID from Customers C join Orders O on C.CustomerID = O.CustomerID GROUP BY C.CustomerID

DECLARE @CustomerID INT
DECLARE @sqltext varchar(4000);

OPEN CURS
FETCH NEXT FROM CURS INTO @CustomerID

WHILE @@FETCH_STATUS = 0  
BEGIN 

SET @sqltext = 'bcp "Select CustomerID, OrderName, OrderQuantity from [DB].[dbo].Customers C join [DB].[dbo].Orders O on C.CustomerID = O.CustomerID WHERE C.CustomerID = ''' 
    + CONVERT(VARCHAR, @CustomerID) 
    + '''" queryout "D:\Test\customer' + CONVERT(VARCHAR, @CustomerID) + '.csv" -c -T -x -t,'

EXEC master..xp_cmdshell @sqltext

FETCH NEXT FROM CURS INTO @CustomerID
END
CLOSE CURS
DEALLOCATE CURS