SQL Server / PowerShell / Exporting data from a SQL Server table to multiple comma-separated value (CSV) files using PowerShell

Export SQL Data to multiple CSV files.

There are many different ways to do this (SSIS, TSQL) but I think that PowerShell could be really efficient tool for such small random tasks.

For this example I will use test table with 17220 rows.

First step is to export whole table to CSV file using export-csv cmdlet. 

Export-CSV converts objects into a series of comma-separated value (CSV) strings and saves the strings to a file.

If you want to find more details about Export-CSV cmdlet and see more usage examples you can read this MS article.

After export is done, you will have one CSV file in you destination folder.

Next step would be to import this CSV file, loop through it and export new CSV for every 1000 rows. Basically, to split this CSV file into multiple CSV files each holding 1000 rows plus the rows difference in the last CSV.

If you want to find more details about Import-CSV cmdlet and see more usage examples you can read this MS article.

At the end you should have something similar to the following picture in your destination folder.

PowerShell script

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *