To export data from SQL Server to a file, you have several options depending on your requirements. The common ways:
- 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:
Example:
sqlcmd -S .\SQL2016 -Q "select top 10 * from Customers where active = 1" -d Sandbox -o customers.txt
From my SQL Server DBA handbook.