MS Excel - join external (SQL) data with local table (sheet)

后端 未结 1 1946
旧巷少年郎
旧巷少年郎 2020-12-04 04:04

I\'m trying to get data from both external source and another sheet of my excel file into one table. What I have in SQL Server is a table of my customers: ╔════╦═════

相关标签:
1条回答
  • 2020-12-04 04:46

    My comment above was merely intended to open a few possibilities which you might have at hand.

    PowerQuery is a free Plug-In for Office 2013. In Office 2016 it is part of Excel and no longer a Plug-In.

    Anyway, you seem to prefer the approach to use a temp table or a table variable on your SQL. Hence, I will elaborate a bit more on this approach:

    In the end you will want a query similar to this one:

    set nocount on;
    declare @tblVAT table
        (
         Country nvarchar(50),
         VAT decimal(9, 7)
        );
    
    insert  into @tblVAT
            (Country, VAT)
    values  (N'Germany', 0.19),
            (N'Frence', 0.20),
            (N'Spain', 0.21);
    
    
    select  tc.Name,
            tc.ID,
            case when tc.Country is null then tv.Country
                 else tc.Country
            end as Country,
            tv.VAT
    from    dbo.tblCustomers as tc
    full outer join @tblVAT as tv
    on      tv.Country = tc.Country;
    

    Note the importance of set nocount on; at the start of the above SQL query. Without that it will not work!

    Once, you have this query you can simply paste it into Excel using the menu DataGet External DataFrom SQL Server. In a first step you will get the customer table and then in a second step refine the query to include the table variable as described above. Here is a short visual summary:

    I guess, at this point the only remaining questions are:

    1. How do you dynamically create the above SQL statement and
    2. how do you get the above table in Excel then updated with this updated SQL statement.

    To dynamically create the above SQL you might want to have a look at the following: Using an array or dictionary as from clause in sql in excel vba

    Just yesterday I answered a similar question where a user wanted to pass the content of an Excel sheet as a dynamically created table to an SQL Server. You can easily adapt (or even use it as is) for your purpose.

    For the last step (update this table in Excel with this new SQL query) you can use the macro recorder and do what I did in the above screenshot. The automatically created code is nothing more / less than what I would propose to you.

    So, there you have it. Let me know if I wasn't clear enough or if you require further details to understand this solution.

    0 讨论(0)
提交回复
热议问题