
There’s more than one way to export data to a file from SQL Server. Which one I reach for depends on whether it’s a one-off or something that has to run every night. These are the ones I use:
- SQL Server Management Studio (SSMS):
- You can export query results to a file directly from SSMS. After executing your query, go to the toolbar and select Query -> Results To -> Results To File. This will prompt you to save the results to a text file with an .rpt extension
- SQLCMD:
- SQLCMD is a command-line utility that allows you to run T-SQL commands and export the results to a file. For example:
sqlcmd -S server_name -d database_name -i input_query.sql -o output_file.txt
This command runs the query in input_query.sql and saves the results to output_file.txt
- PowerShell:
- PowerShell can be used to run SQL queries and export the results to a file. For example:
Invoke-Sqlcmd -ServerInstance "server_name" -Database "database_name" -InputFile "input_query.sql" | Out-File -FilePath "output_file.txt"
This command runs the query in input_query.sql and saves the results to output_file.txt
- Import/Export Wizard in SSMS: right-click the database, choose Tasks -> Export Data, and pick a flat file as the destination. Good for one-off exports to CSV without writing any code.
Example:
sqlcmd -S .\SQL2016 -Q "select top 10 * from Customers where active = 1" -d Sandbox -o customers.txt
For every sqlcmd switch, see Microsoft’s sqlcmd utility documentation.
From my SQL Server DBA handbook.