In this short guide, I’ll show you 2 methods to export query results to CSV in SQL Server Management Studio:
- The quick method for smaller number of records
- The complete method for larger datasets
I’ll also demonstrate how to include the column headers when exporting your results.
Method 1: The quick method to export query results to CSV in SQL Server
To start, run your query in order to get the query results.
For example, I ran a simple query, and got the following table with a small number of records:
To quickly export the query results, select all the records in your table (e.g., by picking any cell on the grid, and then using the keyboard combination of Ctrl + A):
After selecting all your records, right-click on any cell on the grid, and then select ‘Copy with Headers‘ (or simply select ‘Copy’ if you don’t want to include the headers):
Open a blank CSV file, and then paste the results:
The above method can be useful for smaller number of records. However, if you’re dealing with much larger datasets, you may consider to use the second method below.
Method 2: Export query results for larger datasets
Using the same example, you can export the query results to a CSV file by right-clicking on any cell on the grid, and then selecting ‘Save Results As…‘
Next, type a name for your CSV file (for example, ‘query_results’), and then click on Save:
Your CSV file will be saved at the location that you specified:
And if you open the CSV file, you’ll see the exported results (without the column headers):
You may follow the steps below in case you need to include the column headers when exporting your CSV file in SQL Server.
How to include the column headers when exporting query results to CSV in SQL Server
In order to include your column headers, go to Tools, and then select Options…
Then, click on Query Results >> SQL Server >> Results to Grid:
Check the option to ‘Include column headers when copying or saving the results‘ and then click on OK:
You’ll now need to restart SQL Server in order for the changes to be applied.
Then, rerun your query to get the query results:
Right-click on any cell on the grid itself, and then select ‘Save Results As…‘
Type a name for your CSV file, and then press on Save:
Your new CSV would now contain the column headers going forward: