stark
stark

Reputation: 2256

Display foreach loop iteration number in SSIS

I need to keep a check on the iteration number for a foreach loop container task that I am running in Visual Studio 2017. How could I achieve this ?

Upvotes: 4

Views: 8678

Answers (1)

Hadi
Hadi

Reputation: 37348

(1) Count iterations using Expression Task

Task available in SSIS 2012+

In Foreach Loop container, there is no properties that contains the iteration number. You can achieve this by creating a SSIS variable of type Int, with a initial value equal 0. example @[User::Counter]

Inside the Foreach loop container, add an Expression Task with the following expression:

@[User::Counter] = @[User::Counter] + 1

Helpful Links

(2) Count iterations using a Script Task

You can achieve the same process using a Script Task, by creating the counter variable, select it as ReadWrite Variable in the Script Task, and inside the script add a similar line into the Main Function:

Dts.Variables["User::Counter"].Value = Convert.ToInt32(Dts.Variables["User::Counter"].Value) + 1;

References

Displaying data

There are different ways of displaying data. One is to use a script task. Specify your @[User::Counter] variable is in the ReadOnly collection and then emit the value into the run log

    public void Main()
    {
        bool fireAgain = false;
        string message = "{0}::{1} : {2}";
        foreach (var item in Dts.Variables)
        {
            Dts.Events.FireInformation(0, "SCR Echo Back", string.Format(message, item.Namespace, item.Name, item.Value), string.Empty, 0, ref fireAgain);
        }

        Dts.TaskResult = (int)ScriptResults.Success;
    }

A different approach would be to set the Name property of a Task within the Foreach Loop via an expression. Right-click on a Task within the Loop and select Properties. Find the [+]Expressions collection in the Properties section and click the right side ellipses ... and in the new window, select Name in the left hand side and set the right-hand side expression to be

"My Task " + RIGHT("000" + (DT_WSTR,3) @[User::Counter], 3)

This concatenates two strings "My Task" and converts the Counter variable to a string and left pads it with zeroes so it's always a 3 digit number

Upvotes: 6

Related Questions