dylanhogg

Export SQL Server table to csv file with headers using bcp

Jan 28th, 2014
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. rem For more info see: http://stackoverflow.com/questions/1355876/export-table-to-file-with-column-headers-column-names-using-the-bcp-utility-an
  2. rem If you need to supply credentials, replace -T option with -U my_username -P my_password
  3.  
  4. set BCP_EXPORT_SERVER=put_my_server_name_here
  5. set BCP_EXPORT_DB=put_my_db_name_here
  6. set BCP_EXPORT_TABLE=put_my_table_name_here
  7.  
  8. BCP "DECLARE @colnames VARCHAR(max);SELECT @colnames = COALESCE(@colnames + ',', '') + column_name from %BCP_EXPORT_DB%.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='%BCP_EXPORT_TABLE%'; select @colnames;" queryout HeadersOnly.csv -c -T -S%BCP_EXPORT_SERVER%
  9.  
  10. BCP %BCP_EXPORT_DB%.dbo.%BCP_EXPORT_TABLE% out TableDataWithoutHeaders.csv -c -t, -T -S%BCP_EXPORT_SERVER%
  11.  
  12. set BCP_EXPORT_SERVER=
  13. set BCP_EXPORT_DB=
  14. set BCP_EXPORT_TABLE=
  15.  
  16. copy /b HeadersOnly.csv+TableDataWithoutHeaders.csv TableData.csv
  17.  
  18. del HeadersOnly.csv
  19. del TableDataWithoutHeaders.csv
Advertisement
Add Comment
Please, Sign In to add comment