Wednesday 5 April 2017

Dynamically unpivot data

Case
For a client I need to read hundreds of bus route matrices and they all vary in size. This makes it hard to read them dynamically with a Foreach Loop Container because the number of columns differs per file. And I don't want to create hundreds of Data Flow Tasks by hand. Even BIML won't help this time, because the routes change regularly and I don't want to generate and deploy packages every day.
I need to dynamically unpivot data within the Data Flow Task. How do I solve this within SSIS?
Dynamically unpivot data



















Solution
The trick for this case is to read everything as one big column and then dynamically split and unpivot the column in a Script Component Transformation. The unpivot output will always have three columns: Start Station, End Station and Distance. And the good news is that it has only a few lines of relatively easy code.
The solution


























1) Source with one big column
Change your Flat File Connection Manager so that it will read everything as one big column. Make sure the column is big enough to fit all data. For this example I called the column 'ColumnOne'.
Flat File with one column only














2) Script Component Transformation Input
Drag a Script Component on the surface and choose Transformation. Connect it to your source. Then edit the Script Component  and go to the 'Input Columns' page. On that page select the column with all the matrix data as ReadOnly.
Input Columns
























3) Script Component Transformation Input
On the 'Inputs and Outputs' page we need to add the new output columns. For this example I need a StartStation (string), EndStation (string) and the Distance (int).
An other important step is setting the SynchronousInputID property (of Output 0) to 'None'. This makes the transformation asynchronous which means the number of row in could be unequal to the number of rows out. And that means the input buffer with records isn't reused in this component, but a new output buffer will be created.
Inputs and Outputs
























4) The script
Go to the script page, choose C# as scripting language and hit the Edit Script button. And now copy the contents of my Input0_ProcessInputRow method to your Input0_ProcessInputRow method. And there are also two variables called Stations and Distances. They are declared above this method. Copy those to your code and put them on the same place.
I also remove the unused methods PreExecute, PostExecute and CreateNewOutputRows to keep the code clean and mean.
#C# Code
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
#endregion

/// <summary>
/// Split and unpivot data
/// </summary>
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
    // Define two arrays for distances and stations
    // The Stations array will be filled only once
    // The Distances array will change for each row
    string[] Stations;
    string[] Distances;

    /// <summary>
    /// This method is called once for every row that passes through the component from Input0.
    /// </summary>
    /// <param name="Row">The row that is currently passing through the component</param>
    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        // The first time this method executes the Stations array
        // is still empty (null). In the true clause of the if-
        // statement we will fill the Stations array.
        // Therefore the second, third, etc. time this method
        // executes we will go to the false clause of the if-
        // statement.
        if (Stations == null)
        {
            // We know that the first row contains the stations.
            // We will add those to the stations array and use
            // it to determine the end station later on.

            // Split the string from ColumnOne on ; (or your own
            // column separator). The Split returns an array.
            Stations = Row.ColumnOne.Split(';');
        }
        else
        {
            // Now the rows will contain distances (and the StartStation)
            // Split the distances on ; (or your own column separator)
            Distances = Row.ColumnOne.Split(';');

            // Now loop through distances array, but start on 1 (not on 0)
            // because 0 contains the StartStation in the distances array
            for (int counter = 1; counter < Distances.Length; counter++)
            {
                // Add new Row and then fill the columns
                Output0Buffer.AddRow();
                // Get the Distance from the Distance array and convert it to int
                Output0Buffer.Distance = Convert.ToInt32(Distances[counter]);
                // Get the Start station from the distance array (the first item)
                Output0Buffer.StartStation = Distances[0];
                // Get the End station from stations array
                Output0Buffer.EndStation = Stations[counter];
            }
        }
    }
}

4) The result
Now close the Script Component and add more transformations or a destination and see what the Script Component does with your data. I added a dummy Derived Column and Data Viewer to see the data before and after the Script Component. For this file I had 27 rows and columns as input and 676 rows as output (26 * 26).



Related Posts Plugin for WordPress, Blogger...