Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export SQL query data to Excel

I have a query that returns a very large data set. I cannot copy and paste it into Excel which I usually do. I have been doing some research on how to export directly to an Excel sheet. I am running SQL SERVER 2008 on a server running Microsoft Server 2003. I am trying to use the Microsoft.Jet.OLEDB.4.0 data provider and Excel 2007. I've pieced together a small piece of code that looks like this from what I've seen in examples.

INSERT INTO OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'Data Source=C:\Working\Book1.xlsx;Extended Properties=EXCEL 12.0;HDR=YES') SELECT productid, price FROM dbo.product 

However this is not working, I am getting an error message saying

"Incorrect syntax near the keyword 'SELECT'".

Does anyone have any ideas about how to do this or possibly a better approach?

like image 609
JBone Avatar asked Sep 12 '11 14:09

JBone


People also ask

How do I copy query results from SQL Server to Excel?

Method Number 1 – Copy Grid results and paste into Excel After ensuring results to grid turned on, Execute your query, right-click the top left-hand corner of the results grid. Right-click on the database you want to export from. Then Select tasks and “Export Data”. The SQL Server Wizard will startup.


2 Answers

I don't know if this is what you're looking for, but you can export the results to Excel like this:

In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As". One of the export options is CSV.

You might give this a shot too:

INSERT INTO OPENROWSET     ('Microsoft.Jet.OLEDB.4.0',     'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product') 

Lastly, you can look into using SSIS (replaced DTS) for data exports. Here is a link to a tutorial:

http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm

== Update #1 ==

To save the result as CSV file with column headers, one can follow the steps shown below:

  1. Go to Tools->Options
  2. Query Results->SQL Server->Results to Grid
  3. Check “Include column headers when copying or saving results”
  4. Click OK.
  5. Note that the new settings won’t affect any existing Query tabs — you’ll need to open new ones and/or restart SSMS.
like image 57
James Johnson Avatar answered Sep 24 '22 12:09

James Johnson


If you're just needing to export to excel, you can use the export data wizard. Right click the database, Tasks->Export data.

like image 44
brian Avatar answered Sep 23 '22 12:09

brian