Updating sql from excel

SQL Spreads solves some common data management problems for Microsoft SQL Server. It makes it fast and simple to update an SQL table from an Excel spreadsheet. And it gives you the control you need to manage data entered by various users on a collaborative team.
a demo of how to update an SQL table from Excel with SQL Spreads

End users love working in Excel

End users love working in Excel. They know the tool, and they are free to do what they want. That’s the heart of the much-loved Excel application, but also the start of problems for the people taking care of the data. The freedom to add cells and enter “whatever-you-like” values causes huge problems when trying to store and summarize the data in a structured way.

Updating or collecting some “not-available-in-our-systems” data from colleagues is often done by mailing out some Excel file or putting a spreadsheet on a file share.

When users update data in an Excel spreadsheet that should be saved or update in an SQL table, problems like these usually occur:

  • Cells in the spreadsheet can contain invalid data types.
  • There will be problems when users change the layout of the sheet.
  • Difficulties to keep track of previous versions of the Excel spreadsheet.
  • Hard to track who has changed a specific value in a sheet.
  • Troublesome to extract Excel data (with a tool such as SSIS).
  • There can be a delay of several hours between when a user enters the figures and when they appear in the database.

In finance, IT and other fields, structured data is a vital part of the operations. In those fields, you can — literally in minutes — let your end-users update data in structured SQL tables themselves – using Excel. No coding experience or extensive training is necessary.

Here’s information on how you can use SQL Spreads, an Microsoft Excel Add-In, to efficiently and accurately update an SQL Server database from Excel. I will show how to easily bring in your SQL Server tables into Excel for easy updating/management. Then show you how to share the document with your end users and how to keep track of data quality.

How to Update an SQL Table from Excel

To set up an Excel document to work with the data in an SQL Server table, follow these few simple steps:

  1. Download and install the SQL Spreads Excel Add-In.
  2. Go to the SQL Spreads tab in Excel and select Design mode.
  3. A list of databases will appear on the right. Chose the database you are using and select an SQL table to update from Excel.
  4. From the Columns tab you can fine-tune how your table is presented in Excel. You can select the columns you want to update, rearrange them into the order you prefer, and change their names if desired.
  5. When you finished fine-tuning your table, go to the spreadsheet and start updating the data from SQL Server. When you press the Save button the changes will be saved back to your SQL Server table.

There are also several other great benefits of the Designer to easily connect an Excel spreadsheet to a table in SQL Server. For example:

  • Set which columns are editable and which are “read-only”
  • Select which rows in the database are loaded into the Excel spreadsheet
  • Enable Change Tracking and the application will then insert the date and time when a row is changed, as well as the user making the change.
  • Show drop-down lists where the user can select a readable text instead of a key value for columns relating to other tables.

Let your non-technical users update and manage the SQL Server data

After you exit the Design mode you can share your Excel document like any other Excel file. All the settings will follow the document and other users can use your Excel file to update the SQL tables from Excel.

But maybe one of the biggest benefits of SQL Spreads is its ease of use. And the benefits are not only for administrators but also for authorized users throughout your business or enterprise. Non-technical users can use SQL Server-connected Excel documents that you create and share with them. The result will be an accurate and effective collaboration with safeguards including built-in conflict detection.

Assured Data Quality

To get the highest possible quality of data, SQL Spreads uses several methods to guarantee the validity of the entered data:

  • When figures are entered, they are validated against the types of the database columns, and the user receives immediate feedback.
  • Each changed row is tracked in the database to see when a row was changed and by who.
  • A built-in conflict detection system enables safe and easy collaboration.
  • When sharing the document with others, they can be given an Editor role to disable the Design mode to protect the Excel sheet set up that you’ve created.

Automatic Lookup of key values from other tables

Databases contains relations, and a table with keys relating to other tables can be hard to update manually.

When updating a SQL Server table from within Excel, SQL Spreads can lookup those key values in other tables and show drop-down lists where the user can select a readable text instead of a keys value. When the changes are saved to the database, the looked up key will be saved to the database.

Familiar and User-friendly Excel Interface

The data in SQL Server tables can be directly updated from Excel. Users are authenticated using their Windows Login and can only work with the Excel documents for which they are authorized.

Data is automatically validated when users enter their figures through SQL Spreads. And data from other Microsoft Excel documents can be pasted directly into the SQL Server connected documents.

A Low-Stress Solution with High Value to Your Organization

With SQL Spreads, you can:

  • Use Excel to work with data in SQL Server tables.
  • Let non-technical users work with the SQL Server data.
  • Ensure that the entered data is valid.

But more far-reaching benefits can be offered to your business or enterprise by using SQL Spreads. You will immediately see time savings across the board.

  • First, the setup is really fast and simple.
  • Second, when end-users enter data, SQL Spreads will guide them through the right way to enter the data.
  • Third, data owners will have the advantage of being able to easily access centralized data through Excel.
  • Fourth, you can put an end to struggling with importing Excel data using SSIS or maintaining VBA scripts.
  • Lastly, no more troubleshooting and correcting problems created by users altering the spreadsheet.

Those time-consuming processes and frustrations are replaced by SQL Spreads with fast, reliable data management.

Try SQL Spreads First-Hand to Take Control of your SQL Server Data Management

Try SQL Spreads by downloading the new SQL Spreads trial from this page.

There is also a demo video available showing how you can use SQL Spreads to create an Excel document to update the SQL table from Excel.

Editors note: This blog post was originally published for a previous version of SQL Spreads and has been completely revamped and updated for accuracy and comprehensiveness.

Johannes

Johannes Åkesson

Worked in the Business Intelligence industry for the last 15+ years.

Founder of SQL Spreads – the data management
solution to import, update and manage
SQL Server data from within Excel.

There are many ways to do this. I’d recommend something like this, to push data from Excel to SQL Server.

Sub ButtonClick()
'TRUSTED CONNECTION
    On Error GoTo errH
   
    Dim con As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim strPath As String
    Dim intImportRow As Integer
    Dim strFirstName, strLastName As String
   
    Dim server, username, password, table, database As String
   
   
    With Sheets("Sheet1")
           
            server = .TextBox1.Text
            table = .TextBox4.Text
            database = .TextBox5.Text
           
           
            If con.State <> 1 Then
       
                con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
                'con.Open
       
            End If
            'this is the TRUSTED connection string
           
            Set rs.ActiveConnection = con
           
            'delete all records first if checkbox checked
            If .CheckBox1 Then
                con.Execute "delete from tbl_demo"
            End If
       
            'set first row with records to import
            'you could also just loop thru a range if you want.
            intImportRow = 10
           
            Do Until .Cells(intImportRow, 1) = ""
                strFirstName = .Cells(intImportRow, 1)
                strLastName = .Cells(intImportRow, 2)
               
                'insert row into database
                con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
               
                intImportRow = intImportRow + 1
            Loop
           
            MsgBox "Done importing", vbInformation
           
            con.Close
            Set con = Nothing
   
    End With
   
Exit Sub

errH:
    MsgBox Err.Description
End Sub

You can also try this, which uses a Where Clause.

Sub InsertInto()

'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String

'Create a new Connection object
Set cnn = New adodb.Connection

'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PCSQLEXPRESS"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PCSQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes"


'Create a new Command object
Set cmd = New adodb.Command

'Open the Connection to the database
cnn.Open

'Associate the command with the connection
cmd.ActiveConnection = cnn

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText

'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"

'Pass the SQL to the Command object
cmd.CommandText = strSQL


'Execute the bit of SQL to update the database
cmd.Execute

'Close the connection again
cnn.Close

'Remove the objects
Set cmd = Nothing
Set cnn = Nothing

End Sub

Often when you are working on 2 incompatible systems and try to import data from one to another, excel can be a handy tool. I have used excel plenty of times to generate SQL insert / update statements which I could later execute on the database console. Here is a tutorial if you ever have to use excel to generate SQL statements.

The example below shows a simple insert statement generated from customer data in a table. But you can easily extend this technique to come up with complex query statements.

1. Have your data ready

For our purpose the data is arranged like this:

sql-insert-update-query-from-csv-xls-files-data

As you can see, the data has to be in a tabular format so that you can easily generate the query statements. Often you may have to use lookup formulas to clean up the raw data imported in CSV formats.

2. Using excel operator ‘&’ to generate SQL query

Once the data is ready it is very easy to generate the SQL queries using excel string addition operator – &. For the above tabular structure, the concatenate formula would look like:

="insert into customers values('" &B3 &"','" & C3 & "','"&D3&"');" where B3, C3, D3 refer to above table data.

The final queries will look like:

sql-insert-update-query-from-csv-xls-files-final

There are a few practical ways to improve this:

  • Cleaning up data using countif(), sumif(), if() formulas
  • Using vlookup() or countif() to cross-reference items on one table to another


Share this tip with your colleagues

Excel and Power BI tips - Chandoo.org Newsletter

Get FREE Excel + Power BI Tips

Simple, fun and useful emails, once per week.

Learn & be awesome.




  • 40 Comments




  • Ask a question or say something…




  • Tagged under

    development, howto, Learn Excel, Microsoft Excel Formulas, programming, software, sql, technology, text processing




  • Category:

    Learn Excel, technology

Welcome to Chandoo.org

Thank you so much for visiting. My aim is to make you awesome in Excel & Power BI. I do this by sharing videos, tips, examples and downloads on this website. There are more than 1,000 pages with all things Excel, Power BI, Dashboards & VBA here. Go ahead and spend few minutes to be AWESOME.

Read my story • FREE Excel tips book

Advanced Excel & Dashboards training - Excel School is here

Excel School made me great at work.

5/5

Excel formula list - 100+ examples and howto guide for you

From simple to complex, there is a formula for every occasion. Check out the list now.

Calendars, invoices, trackers and much more. All free, fun and fantastic.

Advanced Pivot Table tricks

Power Query, Data model, DAX, Filters, Slicers, Conditional formats and beautiful charts. It’s all here.

Still on fence about Power BI? In this getting started guide, learn what is Power BI, how to get it and how to create your first report from scratch.

Related Tips

40 Responses to “SQL Queries from Excel”

  1. Leonid says:

    I use this method very often.
    I always use =SUBSTITUTE (ColumnWithText,»‘»,»»»)
    to be sure that potential apostrophe in text columns are doubled as required in SQL.

    • Ankit says:

      Awesome ! I don’t use excel very often so the substitute thing is gold to me 🙂 thanks !

  2. @Leonid.. that is a good technique to use substitute to clean up text apostrophes. thanks

  3. Goal:
    Generate update statement in excel where the columns that can be updated are dynamic
    You want the columns which are not updated to keep the same value
    (or not be overwritten with NULL values with the new generated statement)
    the statement can be applied to multiple rows in excel for the same column headers
    (This is why the ‘$’ exist for the column headers that are being set)

    A1 = First_Name
    B1 = Last_Name
    C1 = Middle_Name


    UPDATE PERSONS «&CHAR(10)&
    » SET 1 = 1 «&CHAR(10)&
    IF(LEN(TRIM($A2))=0,»»,», «&$A$1&» = ‘»&$A2&»‘»&CHAR(10))&
    IF(LEN(TRIM($B2))=0,»»,», «&$B$1&» = ‘»&$B2&»‘»&CHAR(10))&
    IF(LEN(TRIM($C2))=0,»»,», «&$C$1&» = ‘»&$C2&»‘»&CHAR(10))&
    » WHERE name = ‘staticordynamicvalue’ AND gender = ‘staticordynamicvalue’
    «
    Output (if all columns are set):
    UPDATE PERSONS SET 1 = 1,
    First_Name = ‘Joe’,
    Last_Name = ‘ORien’,
    Middle_Name = ‘Richard’
    WHERE age = 28 AND gender = ‘m’

    Output (if only First _Name (A1) is set):
    UPDATE PERSONS SET 1 = 1,
    First_Name = ‘Joe’
    WHERE age = 28 AND gender = ‘m’

  4. Possibly my post above is confusing without the actual table to look at. I will do the same example with the table used here. Instead of an insert statement I will generate an update statement for the columns, Cust_Name, Phone & E-mail
    where we can generate an update statement for any column individually or together. 🙂 I hope this can help.
    =”
    UPDATE table “&CHAR(10)&
    ” SET 1 = 1 “&CHAR(10)&
    IF(LEN(TRIM($A2))=0,”»,”,Cust_Name = ‘”&$B3&”‘”&CHAR(10))&
    IF(LEN(TRIM($B2))=0,”»,”, Phone = ‘”&$C3&”‘”&CHAR(10))&
    IF(LEN(TRIM($C2))=0,”»,”, E-mail = ‘”&$D3&”‘”&CHAR(10))&
    ” WHERE Cust_Name = ’Bill Gates’

  5. Thanks, it has been very useful !
    It saved me at least 30 minutes, and time is the most expensive thing in our world…

  6. Kad says:

    Hey Paul,
    What if any of A2, B2, or C2 is a date field?
    The formula above is taking date as string. Any solution?

    • Smitha says:

      Even I faced the same problem. If any of the above columns are date, it is taken  as string. Any work around for this?

  7. I’ve found the string concatenation method works well.

    At the risk of sounding spammy I would mention that
    if it’s something your are doing regularly it might be worth investigating a tools
    that make it easier, such as QueryCell, an excel add-in I’ve developed.

    It gives you a right click menu option that will produce and then customize insert statements for the selected region of Excel data.

    Cheers
    Sam

    • Hi,
      For inserting the excel data to your SQL table, you can create insert statements in excel file according to your columns.
      then just execute the statements all at once, it will insert the required data to sql server table.
      thanks,

      • Ajay Koli says:

        How…?

  8. Chetan Patil says:

    I tried to generate t-sql insert queries from the above example
    =»insert into values(‘» &A2 &»‘,'» & B2& «‘);»
    but it generates on one record instead of all records from excel sheet.
    I’m using Excel 2003 and the excel sheet contains 922 records.

  9. Most data bases can generate DDL for any object but not a lot of them allow generation of INSERT statements for the table data.
    The workaround is to make use of ETL Tools for transferring data across servers. However, there exists a need to generate INSERT statements from the tables for porting data.
    Simplest example is when small or large amount of data needs to be taken out on a removable storage media and copied to a remote location, INSERT..VALUES statements come handy.

    There is a number of scripts available to perform this data transformation task. The problem with those scripts that all of them database specific and they do not work with textiles

    Advanced ETL processor can generate Insert scripts from any data source including text files
    http://www.dbsoftlab.com/generating-insert-statements.html

  10. B.N.Prabhu says:

    Super Aiticle. Thanks for this post.

  11. Archana says:

    Hi ,
    i need a sql query to update a DB in excel 2010..
    i have the query(SQL) for insert in excel as ,
    =»insert into customers values(‘» &B3 &»‘,'» & C3 & «‘,'»&D3&»‘);»

    similarly i need q sql query for update in excel

  12. i want clear formulas only for insert,delete,update,select

  13. Ankit Mahendru says:

    Hi !
    I would like to thank you so much ! This trick saves me a  lot of time. Thank you so much. Really appreciate it !

     
    -Ankit

  14. You may like to take advantage of this unique tool ‘Excel to Database’. 
    (free for 60 days)http://leansoftware.net The Excel-to-Database utility enables you to validate and transfer data from Microsoft Excel or text file to a database table or stored procedure process. Any text data can be pasted into the application, this may be from another Excel sheet or from text files such as CSV format. SQL Server, Access, MySQL, FoxPro .. Application features Some unique features of Excel to Database include: ?Easy to use color coded/traffic light data validation ?Data is validated as soon it is typed or pasted into Excel ?Upload Excel data to a table or stored procedure process ?Allow default values ?Mandatory/must have fields can be specified ?Allow user friendly column names ?Allow excel formula / calculated fields ?Multiple database type support: Microsoft SQL Server, Access, MySQL and others (to be tested) ?Supports Custom SQL scripts, with SQL/Excel merge fields ?Database validation checks ensure you comply with any rules defined within the database ?Multiple Task configuration ?For co-operative use, Tasks can be shared across a network ?Task configuration is password protected http://leansoftware.net 

  15. Manoraj says:

    Its works fine for single record.
    I want to update 1000 records in DB. Can you help me.

  16. Excel database tasks 2.3 (EDT)
    you can now load directly from any source into Excel, validate and upload to most SQL database platforms including SQL Server with automatic transaction wrapping.
    You can also use EDT as a multi-user application by easily designing your own Edit data tasks and deploying EDT on your users workstations.
    Automatically creates UPDATE/INSERT statements based on the primary key.  Default SQL can be modified as you require.
    Makes the best use if Excel power — formatting, formula, validation, conditional formatting..  without creating any problematic spreadsheets!
    Release details on the blog:
    http://leansoftware.net/forum/en-us/blog.aspx
    Thanks for the interest
    Richard

  17. Usman says:

    Thanks for the valueable information, it really help me alot.

     
    Thanks again.

  18. Laercio says:

    As I do with a field of type date?
    = «UPDATE SET business datetime =» & «‘» & A2 & «‘ WHERE ID =» & B2 & «»
    the date is not 03/10/2012 is 41246. Even putting quotes …

  19. Elaein says:

    Please show how to do it properly with dates as well as when those dates are empty. Thanks!

  20. mahesh.S says:

    In a separate column make the date to Text using below formula
    =TEXT(C2,»mm/dd/yyyy») Then Refer this text column in your update statement

  21. cjb says:

    Great post saved me a a load of time on a task i had to complete

  22. sql010 says:

    thanks for sharing article… helpful!

  23. Pooja says:

    Thanks 🙂

  24. […] Excel formula used – http://chandoo.org/wp/2008/09/22/sql-insert-update-statements-from-csv-files/ […]

  25. HSoomro says:

    If any one can help me out with following.
    I want to know a SQL query of below excel formula:
    =LOOKUP(0,-SEARCH(LEFT(F2,LEN($B$2:$B$100))+0,$B$2:$B$100),$A$2:$A$100)

    Excel data is as below;
    Name Codes
    names1 992
    names2 57
    names3 856
    names4 297
    names5 63

    if there is a number (29756789) then it should search in sql by taking the prefix of number (297) from (29756789) and return the name field (name4).
    Codes can be of two digit or three.

    Thanks

  26. Victor R Udeshi says:

    =»INSERT INTO table VALUES (» &A3 &»,'» & B3 & «‘,'»&C3&»‘,'» & D3 & «‘,'» & E3 & «‘,» & F3 & «,» & G3 & «,» & H3 & «,'» & I3 & «‘,» & J3 & «);»

    B3 has date data that looks like 9/22/17 but with the formula above b3 is coming out as 43000?

    how do i fix that?

  27. Mr.Shan says:

    I just want to insert the Excel records in Sql table without Visiting SQL.
    basically i m just want to run a command in Excel Only.
    Help Me..plz..?

  28. Danyal Hussain says:

    Hi I have a question maybe you guys have an answer for me

    =»insert into customers values(‘» &B3 &»‘,'» & C3 & «‘,'»&D3&»‘);» where B3, C3, D3 refer to above table data.

    the above technique works but is there a way to write it so it takes a range instead of individual columns. because I have an extremely wide table

    =»insert into customers values(B3:D3);» where B3, C3, D3 refer to above table data.

  29. Qadir Bux says:

    Awsome

  30. Bhagwat says:

    Its Great Effort to help everyone who working with excel.

  31. Ed says:

    Thanks for the mini-tutorial on SQL from Excel. Didi it several years ago, but couldn’t remember the syntax! All the dialogue was really helpful as well!

Leave a Reply

  • Remove From My Forums
  • Question

  • Hi,

    Can anybody provide a sample code on how to read data from excel sheet and update an sql table.

    thanks for your kind assistance

Answers

  • How to import data from Excel to SQL Server

    This KB article demonstrates how to import data from Microsoft Excel worksheets into Microsoft SQL Server databases by using a variety of methods step by step.


    The samples in this article import Excel data by using:

    SQL Server Data Transformation Services (DTS)
    Microsoft SQL Server 2005 Integration Services (SSIS)
    SQL Server linked servers
    SQL Server distributed queries
    ActiveX Data Objects (ADO) and the Microsoft OLE DB Provider for SQL Server
    ADO and the Microsoft OLE DB Provider for Jet 4.0

    Additionally, about reading data from Excel, please check this thread.

    You need to add reference the excel object library in the COM tab to your project.

      this.openFileDialog1.FileName = «ExcelFile.xls»;
      if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
       {
          Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, «», «», true, Excel.XlPlatform.xlWindows, «t», false, false, 0, true); 
         Excel.Sheets sheets = theWorkbook.Worksheets;
         Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
         for (int i = 1; i <= 10; i++)
         {
         Excel.Range range = worksheet.get_Range(«A»+i.ToString(), «J» + i.ToString());
         System.Array myvalues = (System.Array)range.Cells.Value;

         string[] strArray = ConvertToStringArray(myvalues);
         }
    }

  •  There are several ways to work with Excel files

    1. Use Jet OLEDB Provider. Jet Oledb provider allows to query and update/insert data inside of Excel files without using Excel. But it has some limitations when it does not recognize dates properly in some cases and returns NULL values for some cells if column inside of the spreadsheet has mixed types of data.

    2. Use Microsoft Office Tools for .NET. This way is slower, but gives you more functionality and returns proper data type for each cell. You need to pay attention to releasing all the resources associated with it, because it is COM-based.

    3. Use third party components that could provide desired functionality. I, personally, created my own component to output data into Excel without using Jet or any other tools, just because none of them met my performance requirements.

    Following are some links with the samples

    http://support.microsoft.com/kb/306022/en-us

    http://support.microsoft.com/kb/326548/en-us

    http://support.microsoft.com/kb/307029/en-us

  • Yes, you can and those blank cells would produce NULL values. You could write your own code for the export or to use SQL DTS services


title description author ms.author ms.date ms.service ms.subservice ms.topic monikerRange

Import data from Excel to SQL Server or Azure SQL Database

This article describes methods to import data from Excel to SQL Server or Azure SQL Database. Some use a single step, others require an intermediate text file.

rwestMSFT

randolphwest

03/30/2023

sql

data-movement

conceptual

=azuresqldb-current||>=sql-server-2016||>=sql-server-linux-2017||=azuresqldb-mi-current

Import data from Excel to SQL Server or Azure SQL Database

[!INCLUDE SQL Server Azure SQL Database]

There are several ways to import data from Excel files to [!INCLUDE ssnoversion-md] or to Azure SQL Database. Some methods let you import data in a single step directly from Excel files; other methods require you to export your Excel data as text (CSV file) before you can import it.

This article summarizes the frequently used methods and provides links for more detailed information. A complete description of complex tools and services like SSIS or Azure Data Factory is beyond the scope of this article. To learn more about the solution that interests you, follow the provided links.

List of methods

There are several ways to import data from Excel. You may need to install SQL Server Management Studio (SSMS) to use some of these tools.

You can use the following tools to import data from Excel:

Export to text first ([!INCLUDE ssnoversion-md] and SQL Database) Directly from Excel ([!INCLUDE ssnoversion-md] on-premises only)
Import Flat File Wizard SQL Server Import and Export Wizard
BULK INSERT statement SQL Server Integration Services (SSIS)
BCP OPENROWSET function
Copy Wizard (Azure Data Factory)
Azure Data Factory

If you want to import multiple worksheets from an Excel workbook, you typically have to run any of these tools once for each sheet.

[!IMPORTANT]
To learn more, see limitations and known issues for loading data to or from Excel files.

Import and Export Wizard

Import data directly from Excel files by using the [!INCLUDE ssnoversion-md] Import and Export Wizard. You also can save the settings as a SQL Server Integration Services (SSIS) package that you can customize and reuse later.

  1. In [!INCLUDEssManStudioFull], connect to an instance of the [!INCLUDEssNoVersion] [!INCLUDEssDE].

  2. Expand Databases.

  3. Right-click a database.

  4. Select Tasks.

  5. Choose to Import Data or Export Data:

    :::image type=»content» source=»../../integration-services/import-export-data/media/start-wizard-ssms.jpg» alt-text=»Start wizard SSMS»:::

This launches the wizard:

:::image type=»content» source=»media/excel-connection.png» alt-text=»Connect to an Excel data source»:::

To learn more, review:

  • Start the SQL Server Import and Export Wizard
  • Get started with this simple example of the Import and Export Wizard

Integration Services (SSIS)

If you’re familiar with SQL Server Integration Services (SSIS) and don’t want to run the [!INCLUDE ssnoversion-md] Import and Export Wizard, create an SSIS package that uses the Excel Source and the [!INCLUDE ssnoversion-md] Destination in the data flow.

To learn more, review:

  • Excel Source
  • SQL Server Destination

To start learning how to build SSIS packages, see the tutorial How to Create an ETL Package.

:::image type=»content» source=»media/excel-to-sql-data-flow.png» alt-text=»Components in the data flow»:::

OPENROWSET and linked servers

[!IMPORTANT]
In Azure SQL Database, you cannot import directly from Excel. You must first export the data to a text (CSV) file.

[!NOTE]
The ACE provider (formerly the Jet provider) that connects to Excel data sources is intended for interactive client-side use. If you use the ACE provider on [!INCLUDE ssnoversion-md], especially in automated processes or processes running in parallel, you may see unexpected results.

Distributed queries

Import data directly into [!INCLUDE ssnoversion-md] from Excel files by using the Transact-SQL OPENROWSET or OPENDATASOURCE function. This usage is called a distributed query.

[!IMPORTANT]
In Azure SQL Database, you cannot import directly from Excel. You must first export the data to a text (CSV) file.

Before you can run a distributed query, you have to enable the ad hoc distributed queries server configuration option, as shown in the following example. For more info, see ad hoc distributed queries Server Configuration Option.

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'ad hoc distributed queries', 1;
RECONFIGURE;
GO

The following code sample uses OPENROWSET to import the data from the Excel Sheet1 worksheet into a new database table.

USE ImportFromExcel;
GO
SELECT * INTO Data_dq
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0; Database=C:TempData.xlsx', [Sheet1$]);
GO

Here’s the same example with OPENDATASOURCE.

USE ImportFromExcel;
GO
SELECT * INTO Data_dq
FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
    'Data Source=C:TempData.xlsx;Extended Properties=Excel 12.0')...[Sheet1$];
GO

To append the imported data to an existing table instead of creating a new table, use the INSERT INTO ... SELECT ... FROM ... syntax instead of the SELECT ... INTO ... FROM ... syntax used in the preceding examples.

To query the Excel data without importing it, just use the standard SELECT ... FROM ... syntax.

For more info about distributed queries, see the following articles:

  • Distributed Queries (Distributed queries are still supported in [!INCLUDE sssql19-md], but the documentation for this feature hasn’t been updated.)
  • OPENROWSET
  • OPENDATASOURCE

Linked servers

You can also configure a persistent connection from [!INCLUDE ssnoversion-md] to the Excel file as a linked server. The following example imports the data from the Data worksheet on the existing Excel linked server EXCELLINK into a new [!INCLUDE ssnoversion-md] database table named Data_ls.

USE ImportFromExcel;
GO
SELECT * INTO Data_ls FROM EXCELLINK...[Data$];
GO

You can create a linked server from SQL Server Management Studio (SSMS), or by running the system stored procedure sp_addlinkedserver, as shown in the following example.

DECLARE @RC INT;
DECLARE @server NVARCHAR(128);
DECLARE @srvproduct NVARCHAR(128);
DECLARE @provider NVARCHAR(128);
DECLARE @datasrc NVARCHAR(4000);
DECLARE @location NVARCHAR(4000);
DECLARE @provstr NVARCHAR(4000);
DECLARE @catalog NVARCHAR(128);

-- Set parameter values
SET @server = 'EXCELLINK';
SET @srvproduct = 'Excel';
SET @provider = 'Microsoft.ACE.OLEDB.12.0';
SET @datasrc = 'C:TempData.xlsx';
SET @provstr = 'Excel 12.0';

EXEC @RC = [master].[dbo].[sp_addlinkedserver] @server,
    @srvproduct,
    @provider,
    @datasrc,
    @location,
    @provstr,
    @catalog;

For more info about linked servers, see the following articles:

  • Create Linked Servers
  • OPENQUERY

For more examples and info about both linked servers and distributed queries, see the following article:

  • How to use Excel with SQL Server linked servers and distributed queries

Prerequisite — Save Excel data as text

To use the rest of the methods described on this page — the BULK INSERT statement, the BCP tool, or Azure Data Factory — first you have to export your Excel data to a text file.

In Excel, select File | Save As and then select Text (Tab-delimited) (*.txt) or CSV (Comma-delimited) (*.csv) as the destination file type.

If you want to export multiple worksheets from the workbook, select each sheet, and then repeat this procedure. The Save as command exports only the active sheet.

[!TIP]
For best results with data importing tools, save sheets that contain only the column headers and the rows of data. If the saved data contains page titles, blank lines, notes, and so forth, you may see unexpected results later when you import the data.

The Import Flat File Wizard

Import data saved as text files by stepping through the pages of the Import Flat File Wizard.

As described previously in the Prerequisite section, you have to export your Excel data as text before you can use the Import Flat File Wizard to import it.

For more info about the Import Flat File Wizard, see Import Flat File to SQL Wizard.

BULK INSERT command

BULK INSERT is a Transact-SQL command that you can run from SQL Server Management Studio. The following example loads the data from the Data.csv comma-delimited file into an existing database table.

As described previously in the Prerequisite section, you have to export your Excel data as text before you can use BULK INSERT to import it. BULK INSERT can’t read Excel files directly. With the BULK INSERT command, you can import a CSV file that is stored locally or in Azure Blob storage.

USE ImportFromExcel;
GO
BULK INSERT Data_bi FROM 'C:Tempdata.csv'
   WITH (
      FIELDTERMINATOR = ',',
      ROWTERMINATOR = 'n'
);
GO

For more info and examples for [!INCLUDE ssnoversion-md] and SQL Database, see the following articles:

  • Import Bulk Data by Using BULK INSERT or OPENROWSET(BULK…)
  • BULK INSERT

BCP tool

BCP is a program that you run from the command prompt. The following example loads the data from the Data.csv comma-delimited file into the existing Data_bcp database table.

As described previously in the Prerequisite section, you have to export your Excel data as text before you can use BCP to import it. BCP can’t read Excel files directly. Use to import into [!INCLUDE ssnoversion-md] or SQL Database from a test (CSV) file saved to local storage.

[!IMPORTANT]
For a text (CSV) file stored in Azure Blob storage, use BULK INSERT or OPENROWSET. For an examples, see Example.

bcp.exe ImportFromExcel..Data_bcp in "C:Tempdata.csv" -T -c -t ,

For more info about BCP, see the following articles:

  • Import and Export Bulk Data by Using the bcp Utility
  • bcp Utility
  • Prepare Data for Bulk Export or Import

Copy Wizard (ADF)

Import data saved as text files by stepping through the pages of the Azure Data Factory (ADF) Copy Wizard.

As described previously in the Prerequisite section, you have to export your Excel data as text before you can use Azure Data Factory to import it. Data Factory can’t read Excel files directly.

For more info about the Copy Wizard, see the following articles:

  • Data Factory Copy Wizard
  • Tutorial: Create a pipeline with Copy Activity using Data Factory Copy Wizard.

Azure Data Factory

If you’re familiar with Azure Data Factory and don’t want to run the Copy Wizard, create a pipeline with a Copy activity that copies from the text file to [!INCLUDE ssnoversion-md] or to Azure SQL Database.

As described previously in the Prerequisite section, you have to export your Excel data as text before you can use Azure Data Factory to import it. Data Factory can’t read Excel files directly.

For more info about using these Data Factory sources and sinks, see the following articles:

  • File system
  • SQL Server
  • Azure SQL Database

To start learning how to copy data with Azure data factory, see the following articles:

  • Move data by using Copy Activity
  • Tutorial: Create a pipeline with Copy Activity using Azure portal

Common errors

Microsoft.ACE.OLEDB.12.0″ hasn’t been registered

This error occurs because the OLEDB provider isn’t installed. Install it from Microsoft Access Database Engine 2010 Redistributable. Be sure to install the 64-bit version if Windows and [!INCLUDE ssnoversion-md] are both 64-bit.

The full error is:

Msg 7403, Level 16, State 1, Line 3
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" has not been registered.

Cannot create an instance of OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)»

This indicates that the Microsoft OLEDB hasn’t been configured properly. Run the following Transact-SQL code to resolve this:

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

The full error is:

Msg 7302, Level 16, State 1, Line 3
Cannot create an instance of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

The 32-bit OLE DB provider «Microsoft.ACE.OLEDB.12.0» cannot be loaded in-process on a 64-bit SQL Server

This occurs when a 32-bit version of the OLD DB provider is installed with a 64-bit [!INCLUDE ssnoversion-md]. To resolve this issue, uninstall the 32-bit version and install the 64-bit version of the OLE DB provider instead.

The full error is:

Msg 7438, Level 16, State 1, Line 3
The 32-bit OLE DB provider "Microsoft.ACE.OLEDB.12.0" cannot be loaded in-process on a 64-bit SQL Server.

The OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)» reported an error.

Cannot initialize the data source object of OLE DB provider «Microsoft.ACE.OLEDB.12.0» for linked server «(null)»

Both of these errors typically indicate a permissions issue between the [!INCLUDE ssnoversion-md] process and the file. Ensure that the account that is running the [!INCLUDE ssnoversion-md] service has full access permission to the file. We recommend against trying to import files from the desktop.

The full errors are:

Msg 7399, Level 16, State 1, Line 3
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7303, Level 16, State 1, Line 3
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Next steps

  • Get started with this simple example of the Import and Export Wizard
  • Import data from Excel or export data to Excel with SQL Server Integration Services (SSIS)
  • bcp Utility
  • Move data by using Copy Activity

Like this post? Please share to your friends:
  • Use compound word in a sentence
  • Unique data from excel
  • Updating data in excel
  • Use collocation in a sentence for each word
  • Updating all fields in word