Select from excel query

There are many fine ways to get this done, which others have already suggestioned. Following along the «get Excel data via SQL track», here are some pointers.

  1. Excel has the «Data Connection Wizard» which allows you to import or link from another data source or even within the very same Excel file.

  2. As part of Microsoft Office (and OS’s) are two providers of interest: the old «Microsoft.Jet.OLEDB», and the latest «Microsoft.ACE.OLEDB». Look for them when setting up a connection (such as with the Data Connection Wizard).

  3. Once connected to an Excel workbook, a worksheet or range is the equivalent of a table or view. The table name of a worksheet is the name of the worksheet with a dollar sign («$») appended to it, and surrounded with square brackets («[» and «]»); of a range, it is simply the name of the range. To specify an unnamed range of cells as your recordsource, append standard Excel row/column notation to the end of the sheet name in the square brackets.

  4. The native SQL will (more or less be) the SQL of Microsoft Access. (In the past, it was called JET SQL; however Access SQL has evolved, and I believe JET is deprecated old tech.)

  5. Example, reading a worksheet: SELECT * FROM [Sheet1$]

  6. Example, reading a range: SELECT * FROM MyRange

  7. Example, reading an unnamed range of cells: SELECT * FROM [Sheet1$A1:B10]

  8. There are many many many books and web sites available to help you work through the particulars.

Further notes

By default, it is assumed that the first row of your Excel data source contains column headings that can be used as field names. If this is not the case, you must turn this setting off, or your first row of data «disappears» to be used as field names. This is done by adding the optional HDR= setting to the Extended Properties of the connection string. The default, which does not need to be specified, is HDR=Yes. If you do not have column headings, you need to specify HDR=No; the provider names your fields F1, F2, etc.

A caution about specifying worksheets: The provider assumes that your table of data begins with the upper-most, left-most, non-blank cell on the specified worksheet. In other words, your table of data can begin in Row 3, Column C without a problem. However, you cannot, for example, type a worksheet title above and to the left of the data in cell A1.

A caution about specifying ranges: When you specify a worksheet as your recordsource, the provider adds new records below existing records in the worksheet as space allows. When you specify a range (named or unnamed), Jet also adds new records below the existing records in the range as space allows. However, if you requery on the original range, the resulting recordset does not include the newly added records outside the range.

Data types (worth trying) for CREATE TABLE: Short, Long, Single, Double, Currency, DateTime, Bit, Byte, GUID, BigBinary, LongBinary, VarBinary, LongText, VarChar, Decimal.

Connecting to «old tech» Excel (files with the xls extention): Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:MyFolderMyWorkbook.xls;Extended Properties=Excel 8.0;. Use the Excel 5.0 source database type for Microsoft Excel 5.0 and 7.0 (95) workbooks and use the Excel 8.0 source database type for Microsoft Excel 8.0 (97), 9.0 (2000) and 10.0 (2002) workbooks.

Connecting to «latest» Excel (files with the xlsx file extension): Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Excel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;"

Treating data as text: IMEX setting treats all data as text. Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Excel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";

(More details at http://www.connectionstrings.com/excel)

More information at http://msdn.microsoft.com/en-US/library/ms141683(v=sql.90).aspx, and at http://support.microsoft.com/kb/316934

Connecting to Excel via ADODB via VBA detailed at http://support.microsoft.com/kb/257819

Microsoft JET 4 details at http://support.microsoft.com/kb/275561

My previous article explored using plain SQL to connect and work with other Access databases:

Advanced SQL To Connect With External Databases

Everyone knows that we can create linked table to external databases, but did you know you can actually directly query another database without first setting up a linked table?

This time, I thought I’d show you how you can create SELECT statements that can bind directly to an Excel Workbook to work with the data without the need of Linked Table or advanced VBA coding.

Linked Table Limitation

Yes, it is true, you used to be able to directly edit Excel documents via linked tables, but that ability was lost/removed in Access 2003 and 2002:

Because of legal issues, Microsoft has disabled the functionality in Access 2003 and in Access 2002 that let users change the data in linked tables that point to a range in an Excel workbook.Microsoft — KB904953

This is why turning towards using a direct SQL Query can be so valuable as it allows you to still edit a Workbook directly without the need of VBA automation or some other workaround.

Basic SELECT Statement

Below is the basic syntax to perform a SELECT query on an Excel Workbook:

SELECT *
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:YourFullPathYourWorkBook.xlsx].[WorkSheetName$];

Practical Usage Example

Here’s a concrete example:

SELECT *
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$];

Retrieving a Specific Cell or Range

What if, instead of getting an entire sheet, you only wanted to retrieve a specific range or cell.  Well, it can be done quite easily!  You simply need to add a range definition to the sheet name, as illustrated below:

SELECT * 
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:YourFullPathYourWorkBook.xlsx].[WorkSheetName$XX:XX];

Return a Specific Range

SELECT *
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$C5:G17];

Return a Specific Cell

The same principle is required for a single cell, in that you still have to supply a range!  So you would do:

SELECT *
FROM [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$C5:C5];

Applying a Where Clause

Yes, you can apply where clauses here!

SELECT * 
FROM [Excel 12.0 Xml;HDR=YES;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$]
WHERE [ID] = 13;

Basic Append Query

Below is the basic syntax to perform an UPDATE query on an Excel Workbook:

INSERT INTO [Excel 12.0 Xml;HDR=YES;IMEX=0;Database=C:YourFullPathYourWorkBook.xlsx].[WorkSheetName$] 
('Field1Name', 'Field2Name', 'Field3Name', ...)
VALUES (1, 'SomeValue', 'SomeValue');

Practical Usage Example

Here’s a simple example

INSERT INTO [Excel 12.0 Xml;HDR=NO;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$]
( Company, [Last Name], [First Name] )
VALUES ('McDonalds', 'Kempczinski', 'Chris');

Basic Update Query

Below is the basic syntax to perform an UPDATE query on an Excel Workbook:

UPDATE [Excel 12.0 Xml;HDR=YES;IMEX=0;Database=C:YourFullPathYourWorkBook.xlsx].[WorkSheetName$] 
SET [FieldName] = 'Value'
WHERE [FieldName] = 'Condition';

Practical Usage Example

Here’s a simple example

UPDATE [Excel 12.0 Xml;HDR=YES;IMEX=0;Database=C:DemosContacts.xlsx].[Sheet1$] 
SET [FirstName] = 'Christopher'
WHERE [FirstName] = 'Chris';

Basic DELETE Query

This operation cannot be performed and you will receive an error like:

Microsoft Access Deleteing data in a linked table is not supported by this ISAM.Microsoft Access

Explanation of The Parameters

In case you were wondering, IMEX refers to ‘Import Export mode’ and has 3 possible values: 0,1 or 2.
HDR refers to Header and has 2 possible values: Yes or No.

HDR (Yes/No)
This property will be used to specify the definition of header for each column. If the value is ‘Yes’, the first row will be treated as heading. Otherwise, the heading will be generated by the system like F1, F2 and so on.

IMEX (0/1/2)
IMEX refers to IMport EXport mode. This can take three possible values.

IMEX=0 and IMEX=2 will result in ImportMixedTypes being ignored and the default value of ‘Majority Types’ is used. In this case, it will take the first 8 rows and then the data type for each column will be decided.
IMEX=1 is the only way to set the value of ImportMixedTypes as Text. Here, everything will be treated as text.Gaurang Desai (on Code Project)

IMEX!

For a query to be editable, you must use an IMEX value of 0!  Otherwise, it is read-only.

A Workaround For Linked Tables

As you have seen above, to make queries directly editable, we are controlling the connection used by specifying IMEX=0.

Well, in reality we can do the same thing to a Linked Table to an Excel Worksheet.

The same issue exists with Excel Linked tables.  If you examine the connection string you will get back something like:

Excel 12.0 Xml;HDR=YES;IMEX=2;ACCDB=YES;DATABASE=C:DemosContacts.xlsx

where, by default, Access creates the Linked Tables with an IMEX=2 which doesn’t allow editing.  Thus, the workaround, is to change the IMEX value of the Linked table to 0.  For this I created a very simple procedure:

'---------------------------------------------------------------------------------------
' Procedure : MakeExcelLinkedTableEditable
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Update Excel Linked Tables to make them Editable
'               Change IMEX to 0
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Late Binding  -> none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sTable    : Name of the Excel Linked Table to make editable
'
' Usage:
' ~~~~~~
' Call MakeExcelLinkedTableEditable("Sheet1")
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2022-02-26              Initial Public Release
'---------------------------------------------------------------------------------------
Sub MakeExcelLinkedTableEditable(ByVal sTable As String)
    On Error GoTo Error_Handler
    Dim db                    As DAO.Database
    Dim tdf                   As DAO.TableDef

    Set db = CurrentDb
    Set tdf = db.TableDefs(sTable)
    'Only IMEX=0 is editable!
    tdf.Connect = Replace(Replace(tdf.Connect, "IMEX=1", "IMEX=0"), "IMEX=2", "IMEX=0")
    tdf.RefreshLink

Error_Handler_Exit:
    On Error Resume Next
    If Not tdf Is Nothing Then Set tdf = Nothing
    If Not db Is Nothing Then Set db = Nothing
    Exit Sub

Error_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: MakeExcelLinkedTableEditable" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Sub

So now, you can create a Linked Table to an Excel Worksheet, run this procedure, and it becomes editable.  You can create, queries, forms and be able to work with the data.

Update 2022-03-01 — Excel Connection Fixer

You may like to review the following which offer a interactive form to make the necessary change(s) to make an Excel Linked Table editable.

Making Excel Linked Tables Editable

Many of you are aware of my previous article about linking to Excel spreadsheets In the section entitled ‘A Workaround For Linked Tables’ I provided some VBA code to change the necessary connection property. Knowing that not everyone is comfortable with VBA, I decided to quickly put together a simple form that you can import…

Continue reading

Connection Caching

One quick comment regarding working with Excel in this manner.  While playing around with all of this, trying to figure out what worked and didn’t, I found out the hard way that Microsoft Access does some type of connection caching.  So, I spent some serious time with valid code that wouldn’t work because Access continued to use an old connection I had previously tried out.  Moral of the story, learn from my mistake, close and restart Access when you modify the connection string!

A Few Resources on the Subject

I’d love to provide links to Official documentation on all of this, I have searched, yet found nothing. Lots and lots of posts, but nothing from Microsoft explicitly covering IMEX, HDR. You can find mention here and there, but never a complete authoritative official article, here are the values and what they do. I also found numerous discussions pointing to now long gone MS KB articles.

Fellow MVP Karl Donaubauer just made me aware of his post on the subject, so check that out.  Heck, I never knew he had a website with such information! I’ve provided a translated link as his site is natively German.

donkarls Access-Pages

MSAccess FAQ, Access Developer Conference, SQL Server Developer Conference, .Net Developer Conference, Database Programming Info and Downloads

How to create an MS Query in Excel

You can use Microsoft Query in Excel to retrieve data from an Excel Workbook as well as External Data Sources using SQL SELECT Statements. Excel Queries created this way can be refreshed and rerun making them a comfortable and efficient tool in Excel.

Microsoft Query allows you use SQL directly in Microsoft Excel, treating Sheets as tables against which you can run Select statements with JOINs, UNIONs and more. Often Microsoft Query statements will be more efficient than Excel formulas or a VBA Macro. A Microsoft Query (aka MS Query, aka Excel Query) is in fact an SQL SELECT Statement. Excel as well as Access use Windows ACE.OLEDB or JET.OLEDB providers to run queries. Its an incredible often untapped tool underestimated by many users!

What can I do with MS Query?

example excel ms queryUsing MS Query in Excel you can extract data from various sources such as:

  • Excel Files – you can extract data from External Excel files as well as run a SELECT query on your current Workbook
  • Access – you can extract data from Access Database files
  • MS SQL Server – you can extract data from Microsoft SQL Server Tables
  • CSV and Text – you can upload CSV or tabular Text files

Step by Step – Microsoft Query in Excel

In this step by step tutorial I will show you how to create an Microsoft Query to extract data from either you current Workbook or an external Excel file.

I will extract data from an External Excel file called MOCK DATA.xlsx. In this file I have a list of Male/Female mock-up customers. I will want to create a simple query to calculate how many are Male and how many Female.
MS Query - Sample data

Open the MS Query (from Other Sources) wizard

Go to the DATA Ribbon Tab and click From Other Sources. Select the last option From Microsoft Query.
Create a MS Query (QueryTable)

Select the Data Source

Create a MS Query (QueryTable)Next we need to specify the Data Source for our Microsoft Query. Select Excel Files to proceed.

Select Excel Source File

Excel MS Query - Select Data sourceNow we need to select the Excel file that will be the source for our Microsoft Query. In my example I will select my current Workbook, the same from which I am creating my MS Query.

Select Columns for your MS Query

The Wizard now asks you to select Columns for your MS Query. If you plan to modify the MS Query manually later simply click OK. Otherwise select your Columns.
Create a Microsoft Query (QueryTable)3

Return Query or Edit Query

Create a Microsoft Query (QueryTable)3Now you have two options:

  1. Return Data to Microsoft Excel – this will return your query results to Excel and complete the Wizard
  2. View data or edit query in Microsoft Query – this will open the Microsoft Query window and allow you to modify you Microsoft Query

Optional: Edit Query

MS Query - Edit SQLIf you select the View data or edit query in Microsoft Query option you can now open the SQL Edit Query window by hitting the SQL button. When you are done hit the return button (the one with the open door).

Import Data

When you are done modifying your SQL statement (as I in previous step). Click the Return data button in the Microsoft Query window.MS Query - Import to Excel
This should open the Import Data window which allows you to select when the data is to be dumped.
Create a Microsoft Query (QueryTable)3Lastly, when you are done click OK on the Import Data window to complete running the query. You should see the result of the query as a new Excel table:
Excel MS Query - The result
As in the window above I have calculated how many of the records in the original table where Male and how many Female.

AS you can see there are quite a lot of steps needed to achieve something potentially pretty simple. Hence there are a couple of alternatives thanks to the power of VBA Macro….

MS Query – Create with VBA

If you don’t want to use the SQL AddIn another way is to create these queries using a VBA Macro. Below is a quick macro that will allow you write your query in a simple VBA InputBox at the selected range in your worksheet.
Create MS Query
Just use my VBA Code Snippet:

Sub ExecuteSQL()
    Attribute ExecuteSQL.VB_ProcData.VB_Invoke_Func = "Sn14"
    'AnalystCave.com
    On Error GoTo ErrorHandl
    Dim SQL As String, sConn As String, qt As QueryTable
    SQL = InputBox("Provide your SQL Query", "Run SQL Query")
    If SQL = vbNullString Then Exit Sub
    sConn = "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;;Password=;User ID=Admin;Data Source=" &amp; _
        ThisWorkbook.Path &amp; "/" &amp; ThisWorkbook.Name &amp; ";" &amp; _
        "Mode=Share Deny Write;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    Set qt = ActiveCell.Worksheet.QueryTables.Add(Connection:=sConn, Destination:=ActiveCell)
    With qt
        .CommandType = xlCmdSql
        .CommandText = SQL
        .Name = Int((1000000000 - 1 + 1) * Rnd + 1)
        .RefreshStyle = xlOverwriteCells
        .Refresh BackgroundQuery:=False
    End With
    Exit Sub
ErrorHandl: MsgBox "Error: " &amp; Err.Description: Err.Clear
End Sub

Just create a New VBA Module and paste the code above. You can run it hitting the CTRL+SHIFT+S Keyboardshortcut or Add the Macro to your Quick Access Toolbar.

Learning SQL with Excel

Creating MS Queries is one thing, but you need to have a pretty good grasp of the SQL language to be able to use it’s true potential. I recommend using a simple Excel database (like Northwind) and practicing various queries with JOINs.

Alternatives in Excel – Power Query

Another way to run queries is to use Microsoft Power Query (also known in Excel 2016 and up as Get and Transform). The AddIn provided by Microsoft does require knowledge of the SQL Language, rather allowing you to click your way through the data you want to tranform.
MS Power Query - Get and Transform

MS Query vs Power Query Conclusions

MS Query Pros: Power Query is an awesome tool, however, it doesn’t entirely invalidate Microsoft Queries. What is more, sometimes using Microsoft Queries is quicker and more convenient and here is why:

  • Microsoft Queries are more efficient when you know SQL. While you can click your way through to Transform Data via Power Query someone who knows SQL will likely be much quicker in writing a suitable SELECT query
  • You can’t re-run Power Queries without the AddIn. While this obviously will be a less valid statement probably in a couple of years (in newer Excel versions), currently if you don’t have the AddIn you won’t be able to edit or re-run Queries created in Power Query

MS Query Cons: Microsoft Query falls short of the Power Query AddIn in some other aspects however:

  • Power Query has a more convenient user interface. While Power Queries are relatively easy to create, the MS Query Wizard is like a website from the 90’s
  • Power Query stacks operations on top of each other allowing more convenient changes. While an MS Query works or just doesn’t compile, the Power Query stacks each transform operation providing visibility into your Data Transformation task, and making it easier to add / remove operations

In short I encourage learning Power Query if you don’t feel comfortable around SQL. If you are advanced in SQL I think you will find using good ole Microsoft Queries more convenient. I would compare this to the Age-Old discussion between Command Line devs vs GUI devs


SelectCompare allows for data comparison of Excel spreadsheets, as well as other data sources with a simple, unified interface.

You may be initially anxious about writing an SQL statement to pull data from your Excel, but it is pretty easy!

This post will show you a few examples of writing queries against your spreadsheet that you will be able to use right away for your Excel data comparison.

If you want to find out how to connect to an Excel workbook, please read another post on this blog — Compare Excel Spreadsheets. You may also want to have a look at the blog post DSN-less ODBC Data Sources which shows a few cool connection strings to other data technologies, allowing you to compare data between Excel and CSV for example.

You will see below how to query Excel spreadsheets, specify ranges of columns and rows, and write simple filters that make SQL so powerful.

In a general sense, the data that is stored in the Excel spreadsheet can be represented in two ways — it either has a header with column names, or (more rarely) it doesn’t.

Excel spreadsheet with headers

Let’s assume we have a spreadsheet with headers in the first row as in the following picture.

Excel spreadsheet containing headers

The simplest query you can issue is 

Select * from [Customers$]

Select statement for Excel spreadsheet showing the data results

The query just selects all columns and all rows from the spreadsheet. Excel automatically returns only populated rows and columns.

If you need to limit the number of rows you select from the spreadsheet, use the TOP clause in the select statement:

Select top 3 * from [Customers$]

Select statement for top 3 rows from Excel spreadsheet

If you are interested only in specific columns, you can select only those that you need in the following way:

select CustomerID, CompanyName, ContactName, ContactTitle, Country
from [Customers$]
order by ContactName

Select statement with named columns from Excel spreadsheet

What if my data doesn’t begin in the first row?

It often happens that your spreadsheet has a title and other information at the top. The actual data begin below the title:

Excel report with title starting in the second row

In such case you can specify the range of data you want to select from:

select * from [Customers$A5:K92] order by CompanyName desc

Or just simply

select * from [Customers$A5:K] order by CompanyName desc

Select statement for Excel to read from the range of the spreadsheet

Filtering data in the spreadsheet

You can select only data that you need for comparison by adding a WHERE clause to the query:

select CustomerID, CompanyName, ContactName from [Customers$]
where ContactTitle = 'Owner'

order by ContactName

 Select statement for Excel with WHERE filter clause

Excel spreadsheet without headers

Excel, by default, assumes that the column names of your table are stored in the first row of the table you select from. In some cases you may come across spreadsheets that do not have header information, like in the following illustration:

Excel spreadsheet containing data without header

In this case, if you select data from the spreadsheet, the first row will be treated as column names, which is not what you want.

You have to modify the connection string for your Excel Workbook. Just add the parameter «HDR=NO» to the connection string as displayed below:

Disable header interpretation in Excel connection string

Now, when you select from the spreadsheet, you will notice that Excel provided automatic names for the columns:

Automatic column names for SQL statement for Excel spreadsheet without headers

Usually, you want to have meaningful names for your columns. You can easily apply aliases to your column names, like in the following illustration.

select F1 as CustomerID, F2 as CompanyName, F3 as CustomerName, F4 as CustomerTitle
from [CustomersNoHDR$A1:K]
where F4 ='Owner'

Column aliases for SQL satatement for Excel spreadsheet with data without headers

These are only a few simple examples of queries you can use to select data for your comparison of spreadsheets. You can write more complicated queries, like joining multiple spreadsheets or calling Excel functions in the query to perform certain operations on the attributes, but this is a topic for another occasion.

Other reading

Check also other articles describing various aspects of the usage of SelectCompare.

I described two interesting use cases that use Excel data templates to facilitate data comparison of data produced by two distinct business processes.

Other articles help to understand how to use SelectCompare.Some of them are listed below:

  • Create an Excel baseline for your data
  • How to compare data with a baseline

Содержание

  • Создание SQL запроса в Excel
    • Способ 1: использование надстройки
    • Способ 2: использование встроенных инструментов Excel
    • Способ 3: подключение к серверу SQL Server
  • Вопросы и ответы

SQL в Microsoft Excel

SQL – популярный язык программирования, который применяется при работе с базами данных (БД). Хотя для операций с базами данных в пакете Microsoft Office имеется отдельное приложение — Access, но программа Excel тоже может работать с БД, делая SQL запросы. Давайте узнаем, как различными способами можно сформировать подобный запрос.

Читайте также: Как создать базу данных в Экселе

Язык запросов SQL отличается от аналогов тем, что с ним работают практически все современные системы управления БД. Поэтому вовсе не удивительно, что такой продвинутый табличный процессор, как Эксель, обладающий многими дополнительными функциями, тоже умеет работать с этим языком. Пользователи, владеющие языком SQL, используя Excel, могут упорядочить множество различных разрозненных табличных данных.

Способ 1: использование надстройки

Но для начала давайте рассмотрим вариант, когда из Экселя можно создать SQL запрос не с помощью стандартного инструментария, а воспользовавшись сторонней надстройкой. Одной из лучших надстроек, выполняющих эту задачу, является комплекс инструментов XLTools, который кроме указанной возможности, предоставляет массу других функций. Правда, нужно заметить, что бесплатный период пользования инструментом составляет всего 14 дней, а потом придется покупать лицензию.

Скачать надстройку XLTools

  1. После того, как вы скачали файл надстройки xltools.exe, следует приступить к его установке. Для запуска инсталлятора нужно произвести двойной щелчок левой кнопки мыши по установочному файлу. После этого запустится окно, в котором нужно будет подтвердить согласие с лицензионным соглашением на использование продукции компании Microsoft — NET Framework 4. Для этого всего лишь нужно кликнуть по кнопке «Принимаю» внизу окошка.
  2. Принятие лицензиного соглашение на использование компонента Microsoft NET Framework 4

  3. После этого установщик производит загрузку обязательных файлов и начинает процесс их установки.
  4. Загрузка обязательных файлов

  5. Далее откроется окно, в котором вы должны подтвердить свое согласие на установку этой надстройки. Для этого нужно щелкнуть по кнопке «Установить».
  6. Окно подтверждения согласия на установку надстройки

  7. Затем начинается процедура установки непосредственно самой надстройки.
  8. Установка надстройки

  9. После её завершения откроется окно, в котором будет сообщаться, что инсталляция успешно выполнена. В указанном окне достаточно нажать на кнопку «Закрыть».
  10. Закрытие окна установщика надстройки

  11. Надстройка установлена и теперь можно запускать файл Excel, в котором нужно организовать SQL запрос. Вместе с листом Эксель открывается окно для ввода кода лицензии XLTools. Если у вас имеется код, то нужно ввести его в соответствующее поле и нажать на кнопку «OK». Если вы желаете использовать бесплатную версию на 14 дней, то следует просто нажать на кнопку «Пробная лицензия».
  12. Окно лицензии надстройки XLTools

  13. При выборе пробной лицензии открывается ещё одно небольшое окошко, где нужно указать своё имя и фамилию (можно псевдоним) и электронную почту. После этого жмите на кнопку «Начать пробный период».
  14. Окно активации пробного периода надстройки XLTools

  15. Далее мы возвращаемся к окну лицензии. Как видим, введенные вами значения уже отображаются. Теперь нужно просто нажать на кнопку «OK».
  16. Активация пробной лицензии надстройки XLTools

  17. После того, как вы проделаете вышеуказанные манипуляции, в вашем экземпляре Эксель появится новая вкладка – «XLTools». Но не спешим переходить в неё. Прежде, чем создавать запрос, нужно преобразовать табличный массив, с которым мы будем работать, в так называемую, «умную» таблицу и присвоить ей имя.
    Для этого выделяем указанный массив или любой его элемент. Находясь во вкладке «Главная» щелкаем по значку «Форматировать как таблицу». Он размещен на ленте в блоке инструментов «Стили». После этого открывается список выбора различных стилей. Выбираем тот стиль, который вы считаете нужным. На функциональность таблицы указанный выбор никак не повлияет, так что основывайте свой выбор исключительно на основе предпочтений визуального отображения.
  18. Переход к созданию умной таблицы в Microsoft Excel

    Lumpics.ru

  19. Вслед за этим запускается небольшое окошко. В нем указываются координаты таблицы. Как правило, программа сама «подхватывает» полный адрес массива, даже если вы выделили только одну ячейку в нем. Но на всякий случай не мешает проверить ту информацию, которая находится в поле «Укажите расположение данных таблицы». Также нужно обратить внимание, чтобы около пункта «Таблица с заголовками», стояла галочка, если заголовки в вашем массиве действительно присутствуют. Затем жмите на кнопку «OK».
  20. Окно форматирования таблицы в Microsoft Excel

  21. После этого весь указанный диапазон будет отформатирован, как таблица, что повлияет как на его свойства (например, растягивание), так и на визуальное отображение. Указанной таблице будет присвоено имя. Чтобы его узнать и по желанию изменить, клацаем по любому элементу массива. На ленте появляется дополнительная группа вкладок – «Работа с таблицами». Перемещаемся во вкладку «Конструктор», размещенную в ней. На ленте в блоке инструментов «Свойства» в поле «Имя таблицы» будет указано наименование массива, которое ему присвоила программа автоматически.
  22. Наименование таблицы по умолчанию в Microsoft Excel

  23. При желании это наименование пользователь может изменить на более информативное, просто вписав в поле с клавиатуры желаемый вариант и нажав на клавишу Enter.
  24. Измененное наименование таблицы в Microsoft Excel

  25. После этого таблица готова и можно переходить непосредственно к организации запроса. Перемещаемся во вкладку «XLTools».
  26. Переход во вкладку XLTools в Microsoft Excel

  27. После перехода на ленте в блоке инструментов «SQL запросы» щелкаем по значку «Выполнить SQL».
  28. Переход в окно выполнения SQL надстройки XLTools в программе Microsoft Excel

  29. Запускается окно выполнения SQL запроса. В левой его области следует указать лист документа и таблицу на древе данных, к которой будет формироваться запрос.

    В правой области окна, которая занимает его большую часть, располагается сам редактор SQL запросов. В нем нужно писать программный код. Наименования столбцов выбранной таблицы там уже будут отображаться автоматически. Выбор столбцов для обработки производится с помощью команды SELECT. Нужно оставить в перечне только те колонки, которые вы желаете, чтобы указанная команда обрабатывала.

    Далее пишется текст команды, которую вы хотите применить к выбранным объектам. Команды составляются при помощи специальных операторов. Вот основные операторы SQL:

    • ORDER BY – сортировка значений;
    • JOIN – объединение таблиц;
    • GROUP BY – группировка значений;
    • SUM – суммирование значений;
    • DISTINCT – удаление дубликатов.

    Кроме того, в построении запроса можно использовать операторы MAX, MIN, AVG, COUNT, LEFT и др.

    В нижней части окна следует указать, куда именно будет выводиться результат обработки. Это может быть новый лист книги (по умолчанию) или определенный диапазон на текущем листе. В последнем случае нужно переставить переключатель в соответствующую позицию и указать координаты этого диапазона.

    После того, как запрос составлен и соответствующие настройки произведены, жмем на кнопку «Выполнить» в нижней части окна. После этого введенная операция будет произведена.

Окно выполнения SQL запроса надстройкой XLTools в Microsoft Excel

Урок: «Умные» таблицы в Экселе

Способ 2: использование встроенных инструментов Excel

Существует также способ создать SQL запрос к выбранному источнику данных с помощью встроенных инструментов Эксель.

  1. Запускаем программу Excel. После этого перемещаемся во вкладку «Данные».
  2. Переход во вкладку Данные в Microsoft Excel

  3. В блоке инструментов «Получение внешних данных», который расположен на ленте, жмем на значок «Из других источников». Открывается список дальнейших вариантов действий. Выбираем в нем пункт «Из мастера подключения данных».
  4. Переход в Мастер подключения данных в Microsoft Excel

  5. Запускается Мастер подключения данных. В перечне типов источников данных выбираем «ODBC DSN». После этого щелкаем по кнопке «Далее».
  6. Окно Мастера подключения данных в Microsoft Excel

  7. Открывается окно Мастера подключения данных, в котором нужно выбрать тип источника. Выбираем наименование «MS Access Database». Затем щелкаем по кнопке «Далее».
  8. Окно выбора типа источника Мастера подключения данных в Microsoft Excel

  9. Открывается небольшое окошко навигации, в котором следует перейти в директорию расположения базы данных в формате mdb или accdb и выбрать нужный файл БД. Навигация между логическими дисками при этом производится в специальном поле «Диски». Между каталогами производится переход в центральной области окна под названием «Каталоги». В левой области окна отображаются файлы, расположенные в текущем каталоге, если они имеют расширение mdb или accdb. Именно в этой области нужно выбрать наименование файла, после чего кликнуть на кнопку «OK».
  10. Окно выбора базы данных в Microsoft Excel

  11. Вслед за этим запускается окно выбора таблицы в указанной базе данных. В центральной области следует выбрать наименование нужной таблицы (если их несколько), а потом нажать на кнопку «Далее».
  12. Окно выбора таблицы базы данных в Microsoft Excel

  13. После этого открывается окно сохранения файла подключения данных. Тут указаны основные сведения о подключении, которое мы настроили. В данном окне достаточно нажать на кнопку «Готово».
  14. Окно сохранения файла подключения данных в Microsoft Excel

  15. На листе Excel запускается окошко импорта данных. В нем можно указать, в каком именно виде вы хотите, чтобы данные были представлены:
    • Таблица;
    • Отчёт сводной таблицы;
    • Сводная диаграмма.

    Выбираем нужный вариант. Чуть ниже требуется указать, куда именно следует поместить данные: на новый лист или на текущем листе. В последнем случае предоставляется также возможность выбора координат размещения. По умолчанию данные размещаются на текущем листе. Левый верхний угол импортируемого объекта размещается в ячейке A1.

    После того, как все настройки импорта указаны, жмем на кнопку «OK».

  16. Окно импорта данных в Microsoft Excel

  17. Как видим, таблица из базы данных перемещена на лист. Затем перемещаемся во вкладку «Данные» и щелкаем по кнопке «Подключения», которая размещена на ленте в блоке инструментов с одноименным названием.
  18. Переход в окно подключений в Microsoft Excel

  19. После этого запускается окно подключения к книге. В нем мы видим наименование ранее подключенной нами базы данных. Если подключенных БД несколько, то выбираем нужную и выделяем её. После этого щелкаем по кнопке «Свойства…» в правой части окна.
  20. Переход в свойства базы данных в Microsoft Excel

  21. Запускается окно свойств подключения. Перемещаемся в нем во вкладку «Определение». В поле «Текст команды», находящееся внизу текущего окна, записываем SQL команду в соответствии с синтаксисом данного языка, о котором мы вкратце говорили при рассмотрении Способа 1. Затем жмем на кнопку «OK».
  22. Окно свойств подключения в Microsoft Excel

  23. После этого производится автоматический возврат к окну подключения к книге. Нам остается только кликнуть по кнопке «Обновить» в нем. Происходит обращение к базе данных с запросом, после чего БД возвращает результаты его обработки назад на лист Excel, в ранее перенесенную нами таблицу.

Отправка запроса к базе данных в окне подключения к книге в Microsoft Excel

Способ 3: подключение к серверу SQL Server

Кроме того, посредством инструментов Excel существует возможность соединения с сервером SQL Server и посыла к нему запросов. Построение запроса не отличается от предыдущего варианта, но прежде всего, нужно установить само подключение. Посмотрим, как это сделать.

  1. Запускаем программу Excel и переходим во вкладку «Данные». После этого щелкаем по кнопке «Из других источников», которая размещается на ленте в блоке инструментов «Получение внешних данных». На этот раз из раскрывшегося списка выбираем вариант «С сервера SQL Server».
  2. Переход к окну подключения к серверу SQL Server в Microsoft Excel

  3. Происходит открытие окна подключения к серверу баз данных. В поле «Имя сервера» указываем наименование того сервера, к которому выполняем подключение. В группе параметров «Учетные сведения» нужно определиться, как именно будет происходить подключение: с использованием проверки подлинности Windows или путем введения имени пользователя и пароля. Выставляем переключатель согласно принятому решению. Если вы выбрали второй вариант, то кроме того в соответствующие поля придется ввести имя пользователя и пароль. После того, как все настройки проведены, жмем на кнопку «Далее». После выполнения этого действия происходит подключение к указанному серверу. Дальнейшие действия по организации запроса к базе данных аналогичны тем, которые мы описывали в предыдущем способе.

Окно Мастера подключения данных в программе Microsoft Excel

Как видим, в Экселе SQL запрос можно организовать, как встроенными инструментами программы, так и при помощи сторонних надстроек. Каждый пользователь может выбрать тот вариант, который удобнее для него и является более подходящим для решения конкретно поставленной задачи. Хотя, возможности надстройки XLTools, в целом, все-таки несколько более продвинутые, чем у встроенных инструментов Excel. Главный же недостаток XLTools заключается в том, что срок бесплатного пользования надстройкой ограничен всего двумя календарными неделями.

Еще статьи по данной теме:

Помогла ли Вам статья?

Dear readers of our blog, we’d like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.

SQLS*Plus — best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

18 August 2020

Import of data from Excel to Microsoft SQL Server

Microsoft SQL Server allows you to import data from an Excel file into a database using the built-in T-SQL language in an SQL query. Today I will tell you in detail how it is done, what conditions need to be fulfilled to make this operation successful, tell you about the features of import for the most common cases of SQL server configurations and give specific procedures and practical examples.

I will start by saying that you can import data from Excel to Microsoft SQL Server using “Distributed Queries” and “Linked Servers”. You probably already know this, as I have written about it more than once (references to the relevant materials are given above).

You can access the Excel file and import data into Microsoft SQL Server using T-SQL instructions OPENDATASOURCE, OPENROWSET or OPENQUERY.

However, in the above articles I have missed several important points, one of which is that all SQL Server configurations are different, due to which many have different problems and errors during the execution of distributed queries and calls to related servers.

I also described the way to download data from Excel, which is now outdated, so today I will try to give you a little more information on how to import data from Excel file to Microsoft SQL Server in T-SQL language.

Introduction

So, as I said, the configuration of the SQL server plays a very important role here, in particular, which version of the server is installed, x86 or x64.

If we talk about the latest versions of Microsoft SQL Server 2016-2019, they are only x64 and are installed on 64-bit versions of Windows.

On this basis, I will divide the article into several parts, in each of which I will tell you about features of importing data from Excel for the most common configuration cases and give you a specific order of action.

In order to quickly find out which version of SQL Server is installed on your computer, you can make a simple SQL query

SELECT @@VERSION;

Access to the Excel file and, accordingly, data import into Microsoft SQL Server is performed by special providers (vendors). To work with Excel in Microsoft SQL Server are usually used:

  • Jet.OLEDB.4.0
  • ACE.OLEDB.12.0

In all examples below, I will send a simple SELECT query to select data from an Excel file to check access to the data in the Excel file. To import data (upload data to the database), you can use any method convenient for you, e.g. SELECT INTO or INSERT INTO construction.

In addition, it is recommended to close the Excel file when accessing it in distributed queries, as well as to specify the path to the file without spaces (although modern SQL server can work with spaces).

Import data from Excel 2003 (xls file) into Microsoft SQL Server x86

Step 1 – Check for Microsoft.Jet.OLEDB.4.0 provider on SQL Server

The first thing we need to start with is to check if Microsoft.Jet.OLEDB.4.0 provider is registered on SQL Server, because in this case we need to use that provider. This can be done using the following SQL instruction

EXEC sp_enum_oledb_providers;

The resulting dataset should contain a string with Microsoft.Jet.OLEDB.4.0. If there is no such provider, then most likely there is no Excel 2003 installed in the system and, accordingly, it should be installed.

Step 2 – Granting user rights to a temporary directory

The peculiarity of distributed queries and work with related Excel servers in x86 versions of SQL Server is that regardless of the name of which account sends an SQL query to Excel, this account must have rights to write to the temporary directory of the account under which the SQL Server service itself operates.

Since the OLE DB vendor creates a temporary file during the query in the temporary directory of SQL Server using the credentials of the user executing the query.

Thus, if the SQL Server service runs on behalf of either a local or a network service, it is necessary to give the appropriate permissions to the temporary directory of these services to all users who will send distributed queries and contact the associated Excel server (if the server runs on behalf of the user who sends SQL queries, then such permissions are not required, it already has them).

This can be done using the built-in command line utility icacls.

For example, for a local service, the command will look like this.

icacls C:WindowsServiceProfilesLocalServiceAppDataLocalTemp /grant UserName:(R,W)

For network service

icacls C:WindowsServiceProfilesNetworkServiceAppDataLocalTemp /grant UserName:(R,W)

In place of UserName, provide the name of the user who sends the request.

Step 3 – Enable distributed queries on SQL Server

By default, the ability to use distributed queries, particularly the OPENDATASOURCE and OPENROWSET functions, is prohibited in Microsoft SQL Server, so this feature must be enabled first.

It is enabled using the system stored procedure sp_configure, which is responsible for system parameters of the server. We need to set the Ad Hoc Distributed Queries parameter to 1, to do this we execute the following SQL instruction.

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

Step 4 – Execute SQL query, access to Excel file

Below I will give you some options for accessing the Excel file (TestExcel.xls).

OPENROWSET

SELECT * FROM OPENROWSET
(
'Microsoft.Jet.OLEDB.4.0',
'Excel 8.0; Database=D:TestExcel.xls',
'SELECT * FROM [List 1$]'.
);

OPENDATASOURCE

SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0'),
'Data Source=D:TestExcel.xls;
Extended Properties=Excel 8.0')...[List1$];
Linked Server

--Creation of a linked server
EXEC sp_addlinkedserver @server = 'TEST_EXCEL',
@srvproduct = 'Excel',
@provider = 'Microsoft.Jet.OLEDB.4.0',
@datasrc = 'D:TestExcel.xls',
@provstr = 'Excel 8.0;IMEX=1;HDR=YES;';

--Security settings (authorization)
EXEC dbo.sp_addlinkedsrvlogin @rmtsrvname='TEST_EXCEL',
@useself= 'False',
@locallogin=NULL,
@rmtuser=NULL,
@rmtpassword=NULL;

-- Address to the associated server
SELECT * FROM OPENQUERY (TEST_EXCEL, 'SELECT * FROM [List1$]');
--or 
SELECT * FROM TEST_EXCEL...[List1$];

Import of data from Excel 2007 and higher (xlsx file) into Microsoft SQL Server x86

Step 1 – Check for Microsoft.ACE.OLEDB.12.0 provider on SQL Server

Just like in the previous example, we first check if we have the ISP we need installed, in this case we need Microsoft.ACE.OLEDB.12.0.

EXEC sp_enum_oledb_providers;

Step 2 – Installing Microsoft.ACE.OLEDB.12.0 (32-bit) Provider

If there is no provider, it must be installed. Here’s a link to the ISP download: https://www.microsoft.com/en-us/download/details.aspx?id=13255

Select and download the file corresponding to the x86 architecture (i.e. in the name without x64).

Step 3 – Granting user rights to a temporary directory

In this case, we also give rights to the temporary directory of local or network service to all users who will send SQL queries to the Excel file.

We use the same command line utility icacls.

For local service:

icacls C:WindowsServiceProfilesLocalServiceAppDataLocalTemp /grant UserName:(R,W)

For network service:

icacls C:WindowsServiceProfilesNetworkServiceAppDataLocalTemp /grant UserName:(R,W)

In place of UserName, provide the name of the user who sends the request.

Step 4 – Enable Distributed Queries on SQL Server

Enable the ability to use OPENDATASOURCE and OPENROWSET on Microsoft SQL Server, I repeat that this feature is disabled by default.

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

Step 5 – Configuring Microsoft.ACE.OLEDB.12.0 provider

In this case you will need to additionally configure the provider Microsoft.ACE.OLEDB.12.0. To do this, enable the following provider parameters (specify 0 instead of 1 to disable).

EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

If these parameters are not included, an error is likely to appear, approximately the following

“Message 7399, level 16, state 1, line 25.
The provider of OLE DB “Microsoft.ACE.OLEDB.12.0” for the associated server “(null)” reported an error. The provider did not provide the error data.
Message 7330, level 16, state 2, line 25
We failed to get the string from the OLE DB provider “Microsoft.ACE.OLEDB.12.0” for the associated server “(null)”.

Step 6 – Execute SQL query, access to Excel file

Examples of accessing the Excel file (TestExcel.xlsx).

OPENROWSET

SELECT * FROM OPENROWSET
(
'Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;
Database=D:TestExcel.xlsx',
'SELECT * FROM [List 1$]'.
);

OPENDATASOURCE

SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0'),
'Data Source=D:TestExcel.xlsx;
Extended Properties=Excel 12.0')...[List1$];

Linked Server

--Creation of a linked server
EXEC sp_addlinkedserver @server = 'TEST_EXCEL',
@srvproduct = 'Excel',
@provider = 'Microsoft.ACE.OLEDB.12.0',
@datasrc = 'D:TestExcel.xlsx',
@provstr = 'Excel 12.0;IMEX=1;HDR=YES;';

--Security settings (authorization)
EXEC dbo.sp_addlinkedsrvlogin @rmtsrvname='TEST_EXCEL',
@useself= 'False',
@locallogin=NULL,
@rmtuser=NULL,
@rmtpassword=NULL;

-- Address to the associated server
SELECT * FROM OPENQUERY (TEST_EXCEL, 'SELECT * FROM [List1$]');
-or 
SELECT * FROM TEST_EXCEL...[List1$];

Import of data from Excel (any files) into Microsoft SQL Server x64

Step 1 – Check for Microsoft.ACE.OLEDB.12.0 provider on SQL Server

In this case we also use Microsoft.ACE.OLEDB.12.0 provider, first check if it is registered on the server.

EXEC sp_enum_oledb_providers;

Step 2 – Installing Microsoft.ACE.OLEDB.12.0 (64-bit) provider

In case the provider is not installed, it must be downloaded and installed: https://www.microsoft.com/en-us/download/details.aspx?id=13255

Download the x64 file.

Step 3 – Enable distributed queries on SQL Server

There is also a need to enable the ability to use distributed queries (OPENDATASOURCE and OPENROWSET) on Microsoft SQL Server x64, so first enable it by following exactly the same instruction.

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

Step 4 – Configuring Microsoft.ACE.OLEDB.12.0 provider

In this case, most likely, the provider configuration is not required, so first try to execute SQL queries (refer to data in Excel), and if an error occurs (all with the same message 7399 and 7330), then try to enable the parameters AllowInProcess and DynamicParameters (to disable, specify 0 instead of 1).

EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

Step 5 – Execute SQL query, access to Excel file

Here the same parameters are used in SQL queries as in the previous example. For convenience, I will duplicate them once again.

Examples of accessing the Excel file (TestExcel.xlsx):

OPENROWSET

SELECT * FROM OPENROWSET
(
'Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;
Database=D:TestExcel.xlsx',
'SELECT * FROM [List 1$]'.
);

OPENDATASOURCE

SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0'),
'Data Source=D:TestExcel.xlsx;
Extended Properties=Excel 12.0')...[List1$];

Linked Server

--Creation of a linked server
EXEC sp_addlinkedserver @server = 'TEST_EXCEL',
@srvproduct = 'Excel',
@provider = 'Microsoft.ACE.OLEDB.12.0',
@datasrc = 'D:TestExcel.xlsx',
@provstr = 'Excel 12.0;IMEX=1;HDR=YES;';

--Security settings (authorization)
EXEC dbo.sp_addlinkedsrvlogin @rmtsrvname='TEST_EXCEL',
@useself= 'False',
@locallogin=NULL,
@rmtuser=NULL,
@rmtpassword=NULL;

--Address to the associated server
SELECT * FROM OPENQUERY (TEST_EXCEL, 'SELECT * FROM [List1$]');
--or 
SELECT * FROM TEST_EXCEL...[List1$];

Summing up

Finally, I will group the actions to be performed depending on the release of SQL Server (x68 or x64) and the version of the Excel file (xls or xlsx) into one table for your convenience.

Action / Configure Import Excel 2003 (xls file) into SQL Server x86 Import Excel 2007 (xlsx file) into SQL Server x86 Import Excel (any files) into SQL Server x64
Installing Excel 2003 Yes No No
Installing Microsoft.ACE.OLEDB.12.0 provider No Yes (x86) Yes (x64)
Granting rights to a temporary service directory (if the SQL server is running on behalf of services) Yes Yes No
Configuring Microsoft.ACE.OLEDB.12.0 provider No Yes No (as required)
Connection parameters in SQL queries Microsoft.Jet. OLEDB.4.0 and Excel 8.0 Microsoft.ACE. OLEDB.12.0 and Excel 12.0 Microsoft.ACE. OLEDB.12.0 and Excel 12.0
Enabling distributed queries on SQL Server Yes Yes Yes

That’s all for today, good luck in learning T-SQL!

Import data from Excel to SQL Server table



Tags: Microsoft SQL Server, SQL, sql server, sqls, sqls ms, T-SQL, TSQL

Понравилась статья? Поделить с друзьями:
  • Select excel column in vba
  • Select by color excel
  • Select distinct from excel
  • Select buttons in word
  • Select column word vba