我有以下查询:
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
答案 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