SSIS包:将for循环变量的值存储在数组中

时间:2014-01-04 23:33:13

标签: ssis

我正在创建一个SSIS包,我必须遍历一些选定的文件夹,我想将文件夹名称存储在一个数组中,以跟踪我处理过的文件夹。我可以在SSIS包中保留一个数组并继续在该数组中附加值吗?

1 个答案:

答案 0 :(得分:6)

您可以将for循环变量的值存储在数组中。这样做是一个有点混乱的IMO。正如@billinkc建议的那样,使用“开箱即用”的SSIS功能可能会采用更清洁的方法。但是,这里有一些指示......

让我们一起使用您的方案,其中每个循环都会迭代某些文件(使用Foreach File Enumerator)并且您希望将文件夹名称存储在数组中。

以下是我们将使用的一些变量:

enter image description here

FolderList将是数组,CurrentFile将是for循环变量。最简单形式的包可能如下所示:

enter image description here

在脚本任务中,代码可能如下所示。我选择使用List<string>作为我的数组类型,但您可以使用其他内容,例如ArrayList。 (注意:您需要为以下代码添加System.Collections.GenericSystem.IO的使用语句):

public void Main()
{
    //get current directory
    string directory = Path.GetDirectoryName(Dts.Variables["User::CurrentFile"].Value.ToString());
    List<string> lst = new List<string>();

    // if the FolderList is already a List<string> then set set it to lst
    if ((Dts.Variables["User::FolderList"].Value is List<string>))
    {
        lst = (List<string>)Dts.Variables["User::FolderList"].Value;
    }           

    // if the directory isn't in the list yet, then add it to the list
    if(!lst.Contains(directory))
    {
        lst.Add(directory);
    }

    // update our variable with the List<string>
    Dts.Variables["User::FolderList"].Value = lst;

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

每次执行Script Task时,您都会在阵列中添加一个新文件夹。完成每个循环后,您可能需要检查数组的值。您可以使用Script Task(类似于我们上面所做的)来执行此操作:

List<string> lst = (List<string>)Dts.Variables["User::FolderList"].Value;
// do stuff with lst

你也可以使用for循环遍历数组中的值(使用Foreach From Variable Enumerator),这是我刚刚学习的内容(谢谢!)。只需将变量设置为枚举到数组变量(此处为FolderList),并在Variable Mappings中将另一个变量(例如CurrentFolder)指定为索引0。这适用于List<string>,但我不确定它可以使用的其他集合类型。