How can I use a foreach loop container in SSIS to

2020-04-26 05:02发布

问题:

I have an SSIS package that's updating a couple tables using scripts and a foreach container among a couple other things. I'm using SqlConnection and SqlCommand to call this query in a script task before the foreach container:

SELECT TOP 10 DirectoryID, DirectoryPath FROM ProjectDirectory ORDER BY LastAudit

and am using SqlDataReader to add them to a multidimensional array[10,2]. I assign the array to an object variable DirectoryList so that I can iterate through it in a foreach loop container. It should look like { {"1", "C:\Folder1"}, {"2", "C:\Folder2"}, ...} I believe.

The issue is that I just began using this software a couple days ago, and am confused at how the foreach loop container loops through the DirectoryList variable. At the moment, in the collection tab of the container, I have the Enumerator set to Foreach From Variable Enumerator, with the variable set as User::DirectoryList. I have variables User::DirectoryID set to index 0, and User::DirectoryPath set to index 1. I'm trying to get it to loop through just the top level of the array, so that in each loop the ID and path variables are assigned to "1" and "C:\Folder1", and then next time it passes through the loop they are assigned to "2" and "C:\Folder2", etc. I have a script component that uses the path to find some info, and I use the id to update the correct row of an sql table.

To debug, I'm having it show me the ID and path MessageBox.Show(Variables.DirectoryID + ", " + Variables.DirectoryPath) of the first iteration, and it's showing "8, 8". The 8 corresponds to the id of the row that should show up first. The next time it runs through, it gives me the correct path twice, "C:\Folder1, C:\Folder1". So apparently the variable mapping is not working, it's mapping both variables to the same index. In any case It's not working, so I'm thinking that either (and maybe both?) the Foreach From Variable Enumerator is not the one I should choose, or that I can't use a multidimensional array in a foreach container. I've searched and found nothing and this all may be hard to understand, but any suggestions?

回答1:

ok, you actually dont have to do that way. Since your source is a t-sql query you could have ran it with an "execute sql task". But that's fine, it can be done this way too. I'm actually working on a package right now that get a result set into a datatable on a script task and loads it into a object variable, like you do with your DirectoryList.

To read the values, just configure your loop like this, where the variable is the Object variable:

and on the mappings tab, like this: where the variable is the package variable where you want the value of the first column (index 0) to be placed in. You can have as many indexes as you have columns on your result set.

and that's it, inside your loop you will have access to your variables with the current values