Friday, March 18, 2016

SQL Server: Using BCP to export table (including header) to CSV

If we have to export a table to CSV file. There is a simple way to do this by BCP. 

BCP "DECLARE @colnames VARCHAR(max);SELECT @colnames = COALESCE(@colnames + ',', '') + column_name 
from AX2012_Train.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='BANKPARAMETERS'; 
select @colnames;" queryout e:\test\HeadersOnly.csv -c -T 

BCP AX2012_Train.dbo.BANKPARAMETERS out e:\test\TableDataWithoutHeaders.csv -c -t, -T 

copy /b e:\test\HeadersOnly.csv+e:\test\TableDataWithoutHeaders.csv e:\test\TableData.csv

del e:\test\HeadersOnly.csv
del e:\test\TableDataWithoutHeaders.csv

However this way isn't a best solution to extract table in Dynamics AX 2012 because the column of AX table doesn't sort in the ascending order. (Some field such as RecId, DataAreaId will be put at the last)  But I'm sure this code will be useful in the general case.

No comments:

Post a Comment