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

2 ssis

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

gan*_*way 6

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

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

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

在此输入图像描述

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

在此输入图像描述

在脚本任务中,代码可能如下所示.我选择使用a 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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