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

/ Published in: SQL
Save to your folder(s)

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

Copy this code and paste it in your HTML
  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.)
  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:
  9. sp_configure 'show advanced options', 1
  10. reconfigure
  11. GO
  12. sp_configure 'Ad Hoc Distributed Queries', 1
  13. reconfigure
  14. GO
  16. You can now USE the below query TO import DATA FROM Excel 2007/2003 (.xlsx/xls) sheet INTO SQL Server.
  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$]
  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..)
  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:
  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


RSS Icon Subscribe to comments

You need to login to post a comment.