How can I export a query result to a .csv file in SQL Server 2008?
-
possible duplicate of How to export data as CSV format from SQL Server using sqlcmd? – Martin Smith Jul 2 '10 at 21:38
-
Do you need your delimiter escaped? Most of the answers so far assume you do not, which isn't really all that CSV. – Nick Oct 6 '14 at 17:02
-
@Nick - generally delimiters are contained with a string only, and they typically have quotes around them. See my answer to see the solution to this. stackoverflow.com/questions/6115054/… – MacGyver Sep 18 '15 at 20:50
-
Related post - Export table from database to csv file, SQL Server 2008 - use cmd to output with headers to .csv & Saving results with headers in Sql Server Management Studio. – RBT Mar 18 '19 at 9:51
-
I sometimes use Python – LV98 May 26 '20 at 14:53
- Open SQL Server Management Studio
- Go to Tools > Options > Query Results > SQL Server > Results To Text
- On the far right, there is a drop down box called Output Format
- Choose Comma Delimited and click OK
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
-
11The answer is a bit misleading... When you press
Ctrl+Shift+F
, it only changes the output mode, it doesn't affect the results if you already ran the query. In order for this to be reflected, you have to re-run the query. When you run it in "Results to File" mode, it should prompt you for where you would like to save the results. – qJake Jul 17 '14 at 17:01 -
3Should be Go to Tools > Options > Query Results > SQL Server > Results To Text – congusbongus Jul 22 '14 at 5:21
-
47Re-running the query wasn't enough for me. I had to close the query window, open a new one and then run the query again. – Breandán Sep 5 '14 at 14:29
-
3Confirmed @Breandán comment. The new settings won't apply to currently opened query window, must close them and re-run the query. – Shinigamae Jun 22 '15 at 8:14
-
5One thing I had to do was export it as the default RPT extension. After doing that you can simply rename it to a CSV and it works. – Thomas Bennett Jul 29 '16 at 17:36
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!
-
1Only problem is that this method seems to not let you set any options. For example all the NULLs show in output files as "NULL", etc. Perhaps there is a way to set this that I don't know about, however. – Noah Sep 6 '13 at 7:36
-
15Amazingly even in SSMS 2012, this does not properly quote text for CSV. A comma or new line within a CHAR/VARCHAR should be quoted, but is not. That causes data to shift into new columns or into a new line. – Eric J. Dec 7 '14 at 22:08
-
4
-
9@Don this does give column headers if you go into "Query"->"Query Options...", grid tab, and check "include column headers when copying or saving results" – Rob Wise Jun 6 '15 at 6:59
-
7
You can use PowerShell
$AttachmentPath = "CV File location"
$QueryFmt= "Query"
Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $QueryFmt | Export-CSV $AttachmentPath
-
Thank you! This was the only suggestion that worked for me. Handles escaping properly – emertechie Apr 30 '13 at 21:22
-
3+10 if I could. Only answer that handles escaping. To get this to run, I had to add two lines at the top of the script:
Add-PSSnapin SqlServerCmdletSnapin100
andAdd-PSSnapin SqlServerProviderSnapin100
. – Eric J. Dec 7 '14 at 22:28 -
if you face timeout add the querytimeout so e.g.
Invoke-Sqlcmd -ServerInstance MySQLserver123 -Query $QueryFmt -querytimeout 600 | Export-CSV $AttachmentPath
– Tilo Apr 6 '17 at 16:44 -
1As Powershell newbie I needed to install the SqlServer Module:
Install-Module -Name SqlServer
(but didn't need to snap in those Cmdlets). Also, I'd saved the commands in a script, which wouldn't run until I'd changed the execution policy:Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
. – sandyscott Dec 19 '19 at 12:00 -
@sandyscott I'm a Powershell newbie as well, so thank you. Anyway I think that in this case a
RemoteSigned
execution policy will suffice. – BigBother Jun 6 '20 at 21:21
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).
- Copy the query.
- In Object Explorer right-click on the database in question.
- Select "Tasks" >> "Export Data..."
- Configure your datasource, and click "Next".
- Choose "Flat File" or "Microsoft Excel" as destination.
- Specify a file path.
- If working with a flat file, configure as desired. If working with Microsoft Excel, select "Excel 2007" (previous versions have a row limit at 64k)
- Select "Write a query to specify the data to transfer"
- Paste query from Step 1.
- Click next >> review mappings >> click next >> select "run immediately" >> click "finish" twice.
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"
-
1if you face timeout add the querytimeout so e.g.
Invoke-Sqlcmd -ServerInstance MySQLserver123 -Query $QueryFmt -querytimeout 600 | Export-CSV $AttachmentPath
– Tilo Apr 6 '17 at 16:43
Building on N.S's answer, I have a PowerShell script that exports to a CSV file with the quote marks around the field and comma separated and it skips the header information in the file.
add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100
$qry = @"
Select
*
From
tablename
"@
Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $qry | convertto-CSV -notype | select -skip 1 > "full path and filename.csv"
The first two lines enable the ability to use the Invoke-SqlCmd command-let.
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.
Using the native SQL Server Management Studio technique to export to CSV (as @8kb suggested) doesn't work if your values contain commas, because SSMS doesn't wrap values in double quotes. A more robust way that worked for me is to simply copy the results (click inside the grid and then CTRL-A, CTRL-C) and paste it into Excel. Then save as CSV file from Excel.
You could use QueryToDoc (http://www.querytodoc.com). It lets you write a query against a SQL database and export the results - after you pick the delimiter - to Excel, Word, HTML, or CSV
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
as @Slogmeister Extraordinaire Quoted is correct.
One need to have 1> File already present with columns 2> One need to have Office installed
Errors faced
1
Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"."
2
Msg 15281, Level 16, State 1, Line 1 SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', search for 'Ad Hoc Distributed Queries' in SQL Server Books Online.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 0
RECONFIGURE
GO
If you don't want to use Powershell, this answer is a variation on 8kb's great answer. The only difference is that instead of selecting CSV as the output format, select Tab Delimited. This way if there are commas in your data, it won't skip cells in Excel. Also, if you have Excel's default delimiter set to tabs, you can simply do a copy-all of the SSMS query results (CTRL-A, CTRL-C) and paste into Excel (no need to save as a file and import to Excel):
- In SSMS Go to Tools > Options > Query Results > SQL Server > Results To Text
- Change output format on far right to Tab Delimited
- Click OK
Now you can execute your query, then do a CTRL-A to select all the results, then CTRL-C to copy to clipboard, then switch to Excel 2013 (may work in 2007 too, not sure) and paste -- assuming Excel's default delimiter is set to tab.
One more method worth to mention here:
SQLCMD -S SEVERNAME -E -Q "SELECT COLUMN FROM TABLE" -s "," -o "c:\test.csv"
NOTE: I don't see any network admin let you run powershell scripts
-
1FYI, this answer is already discussed in more details in the "possible duplicate" link to stackoverflow.com/questions/425379/… – mtone Sep 10 '20 at 6:20
I hope 10 years isn't too late, I used this in Windows Scheduler;
"C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE"
-S BLRREPSRVR\SQLEXPRESS -d Reporting_DB -o "C:\Reports\CHP_Gen.csv" -Q "EXEC dbo.CHP_Generation_Report" -W -w 999 -s ","
It opens sql command .exe and runs a script designed for sql command. The sql command script is very easy to use with a few google searches and trial and error. You can see that it picks a database, defines output location and executes a procedure. The procedure is just a query selecting which rows and columns to display from a table in the database.
Yes, all these are possible when you have the direct access to the servers. But what if you have only access to the server from a web / application server? Well, the situation was this with us a long back and the solution was SQL Server Export to CSV.