0

I am trying to upload individual ListObject tables in excel to SQL tables in a database.

I have already wrote code that simply generates an SQL query string and executes - this works but it's not easily maintainable.

So I found this technique: https://stackoverflow.com/a/11268550/1610402

This allows me to fill a data table and bulk insert that into SQL; with column mapping capabilities if they are required.

However my table structure in Excel differs more than simply column 'names' to avoid redundant data.

Therefore I need to map columns from Excel (example):

Column1    Column2   '2015'  '2016'  '2017'  '2018'  '2019'  '2020'
1          1          0.1     0.2     0.3     0.35    0.375   0.4
1          2          0.1     0.2     0.3     0.35    0.375   0.4

To columns in SQL, like the following:

Column1    Column2    Year    Value
1          1          2015    0.1
1          1          2016    0.2
1          1          2017    0.3
1          1          2018    0.35
1          1          2019    0.375
1          1          2020    0.4
1          2          2015    0.1
1          2          2016    0.2
1          2          2017    0.3
1          2          2018    0.35
1          2          2019    0.375
1          2          2020    0.4

Is there a better way of doing this in C# .Net or should I stick with my nested for loop and string builder?

1 Answer 1

1

The concept of what you want is called 'unpivoting'. Whether you do this in C# or is not of importance, since you can simply load the first data in SQL-Server and unpivot this data by

SELECT IDENTITY(int,1,1) as RowId, Column1, Column2, [Year], [Value]
INTO newTable
FROM (
   SELECT Column1,Column2,[2015],[2016],[2017],[2018],[2019],[2020] FROM oldTable
) as source
UNPIVOT
(
   [Value] for [Year] in [2015],[2016],[2017],[2018],[2019],[2020]
) as target

The square brackets are required to make these strings appear as column names in stead of numbers or reserved words.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.