In SQL Server, how do I export the results of a query to a txt file. I tried tools>options>results to file. But this appears to have saved the Messages the query generated instead of the Results the query generated.
3 Answers
Options:
- Use sqlcmd at the command line to execute your SQL statement; the results will arrive as text and can be trivially saved.
- Use bcp at the command line to execute your SQL statement with the "queryout" parameter.
- Use SSMS to grid as you are, right-click the upper left cell of the results pane and use the Save Results As... option
- Use SSMS to file; this will of course save the file on the machine SSMS is running on. Tools->Options->Results to file is where you set options like delimiter, maximum size, and so on. Instead, you want Query->Results To->Results to File or Ctrl-Shift-F (by default)
- Other non-SQL ways like Powershell or any application language or MS Access or Excel with a DSN data source or SSIS or many many many other ways.
A manual way of achieving it is to CRTL+T
on your SSMS to enable the option Results to Text. Execute your query and right click the Results > Save results as > Save as Type > All Files
and name your file something.txt.
-
Thanks for the answers Ronaldo. It's not working though, perhaps because I am accessing SQL Server through a VDI? Control T does not illicit anything, and I tried to save to text via Tools>Options>Results to Text, but that doesn't work for me either.– JimboNov 29, 2022 at 21:50
-
I just ran SELECT * FROM SYSDATABASES successfully. It did something. Not sure what.– JimboNov 29, 2022 at 21:54
-
@Jimbo your problem is not related to using a VDI. That query
SELECT * FROM SYSDATABASES
was just an example of a query to have a result to print and post on my answer. What version of SSMS (Management Studio) are you using? Did you hitCTRL+T
after you had a tab open to run a query?– RonaldoNov 29, 2022 at 23:29
If you are not restricted only to SSMS, you can use Powershell
Invoke-Sqlcmd -ServerInstance MyInstance -Database MyDB -Query "SELECT * FROM Mytable" | Export-CSV "C:\MyResults.csv"