T-SQL: Export Table to Excel

2. December 2009 20:31

SQL Server T-SQL  3 Comments

What you do to export data from SQL to excel. You use data import/export wizard or just simply execute the select query and copy the whole lot of data in an excel file with headers. Copy and paste the data in the excel sheet is the quickest possible solution I can see...but what if you have to data through your code? Still there are many possible ways to accomplish this but how many lines of code you have to write to achieve this? maybe most of the people definately have a simple and reliable way. Ok...lets do this using T-SQL query. The only problem I see here is that you must have a excel file in the location defined in the query before you execute the query.

In one of our application we maintain log in a sql table for all the tasks done in the whole day. The administrator of the application want to take a look at all the tasks done by a particular user, he didn't want any UI to look into this instead he asks us to generate a report at the end of the day in excel on a button click. So lets see the code.

Execute the below query to set the configuration of SQL Server to 1. In my case there was no change as I already executed this query in the past. But, most probably you will see a change in the your case the value could be changed from 0 to 1.

EXEC sp_configure 'show advanced options', 1;
GO RECONFIGURE;
GO EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
GO RECONFIGURE;
GO

After you set the configuration option execute a normal select query to get all the column names and paste them in the excel sheet. Then save the excel sheet in your local hard drive.

Select TOP 0 * From Person.Address

--For Office 2003 (.XLS) format
INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=c:\contact.xls;','SELECT * FROM [Sheet1$]')SELECT * FROM authors

--For Office 2007 (.XLSX) format
INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=c:\contact.xlsx;','SELECT * FROM [Sheet1$]')SELECT * FROM authors
Currently rated 5.0 by 2 people

Comments (3)

Francisco Valdez Francisco Valdez
9/21/2011 1:28:27 AM #

this error is indicated Msg 7308, Level 16, State 1, Procedure exporta_Excel_SIAT, Line 11 OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode.

Francisco Valdez Francisco Valdez
9/21/2011 1:28:51 AM #

this error is indicated Msg 7308, Level 16, State 1, Procedure exporta_Excel_SIAT, Line 11 OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode.

Steve Steve
11/3/2011 6:52:26 PM #

The 'single-threaded apartment mode' would suggest you're running SQLExpress or possibly Compact edition. You can only run distributed queries from a full version of SQL Server.

Add Comment

Visit blogadda.com to discover Indian blogs Computers Blogs