However, if you prefer to export SQL query results to a text file via a Wizard, we have your back. To begin with, right-click the database in SQL Server Management Studio or SSMS. Then, select the Import or Export data option and head to Export Data under Tasks. Next, open the SQL Server Import and Export wizard.
Here's a full screen version of that image, below
This will show your query results as comma-delimited text.
To save the results of a query to a file: Ctrl + Shift + F
I know this is a bit old, but here is a much easier way...
Run your query with default settings (puts results in grid format, if your's is not in grid format, see below)
Right click on grid results and click "Save Results As" and save it.
If your results are not in grid format, right click where you write the query, hover "Results To" and click "Results To Grid"
Be aware you do NOT capture the column headers!
Good Luck!
You can use PowerShell
$AttachmentPath = "CV File location"
$QueryFmt= "Query"
Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $QueryFmt | Export-CSV $AttachmentPath
If the database in question is local, the following is probably the most robust way to export a query result to a CSV file (that is, giving you the most control).
After going through this process exhaustively, I found the following to be the best option
PowerShell Script
$dbname = "**YOUR_DB_NAME_WITHOUT_STARS**"
$AttachmentPath = "c:\\export.csv"
$QueryFmt= @"
**YOUR_QUERY_WITHOUT_STARS**
"@
Invoke-Sqlcmd -ServerInstance **SERVER_NAME_WITHOUT_STARS** -Database $dbname -Query $QueryFmt | Export-CSV $AttachmentPath -NoTypeInformation
Run PowerShell as Admin
& "c:\path_to_your_ps1_file.ps1"
Use T-SQL:
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName
But, there are a couple of caveats:
You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.
The .CSV file will have to exist already. If you're using headers (HDR=YES
), make sure the first line of the .CSV file is a delimited list of all the fields.
MS Excel -> Data -> New Query -> From Database ..follow the steps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With