Posted By

hairajeshk on 08/04/10


Tagged


Versions (?)

Import data into SQL Server using the ad hoc distributed queries from Excel


 / Published in: SQL
 

Import data into SQL Server using the ad hoc distributed queries from Excel

  1. There are many ways TO import DATA FROM Excel INTO SQL Server. Some of them are AS below:
  2. USING SQL Server Integration Services. (This technique allows very detailed control over the DATA being imported but IS complex & time-consuming TO SET up.)
  3. • SQL Server linked servers (This technique requires that you CREATE a permanent linked server pointing TO the Excel source file.)
  4. • SQL Server ad-hoc distributed queries (This IS the quickest way TO import DATA. It creates a TEMPORARY linked server TO the Excel sheet ON the fly & pulls the DATA.)
  5.  
  6. how TO import DATA INTO SQL Server USING the ad hoc distributed queries.
  7. First of ALL, you need TO make sure that "Allow Ad Hoc Distributed Queries" OPTION IN SQL Server Surface Area Configuration window IS SET enabled. This can be done AS below:
  8.  
  9. sp_configure 'show advanced options', 1
  10. reconfigure
  11. GO
  12. sp_configure 'Ad Hoc Distributed Queries', 1
  13. reconfigure
  14. GO
  15.  
  16. You can now USE the below query TO import DATA FROM Excel 2007/2003 (.xlsx/xls) sheet INTO SQL Server.
  17.  
  18. CREATE TABLE TestTable (id int, name varchar(100))
  19. GO
  20. INSERT INTO TestTable
  21. SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0', 'Data Source=C:\test\Data.xlsx;Extended Properties=Excel 8.0')...[Sheet1$]
  22.  
  23. Here, we CREATE a SQL Server TABLE called TestTable AND then pull the DATA FROM Sheet1 IN the source file C:\test\DATA.xlsx INTO the TABLE. Note that we need TO append the Excel sheetname WITH a $ symbol when importing the DATA INTO SQL Server. Also, make sure the DATA types are mapped correctly. (i.e. the query doesn’t try TO INSERT a character value INTO an integer COLUMN IN SQL Server AND so ON..)
  24.  
  25. IN case you don’t have the 'Microsoft.ACE.OLEDB.12.0' provider installed ON the system running SQL Server, the above query will error out. IN that case, you can USE the Microsoft.Jet.OLEDB.4.0 (IF installed) TO import DATA only FROM Excel 2003 sheet. Also note that there IS no Microsoft.Jet.OLEDB.4.0 provider FOR 64-bit systems. So, the below query will error out ON 64-bit systems. The query IS:
  26.  
  27. CREATE TABLE TestTable (id int, name varchar(100))
  28. GO
  29. INSERT INTO TestTable
  30. SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'Data Source=C:\test\Data.xlsx;Extended Properties=Excel 5.0')...[Sheet1$]

Report this snippet  

You need to login to post a comment.