如何将自定义平面文件头中的值提取到变量中?

时间:2013-05-15 12:25:38

标签: etl ssis

我遇到这个问题已经有一段时间了,我不知道。我正在尝试上传多个具有日期的CSV文件,但我希望将日期存储为日期变量,因此我使用日期变量在表格中使用脚本组件构成列的一部分,我不知道如何创建日期作为日期SSIS中的变量。

在Excel中打开时,CSV文件的外观如下所示。

CSV数据1:

Relative Date: 02/01/2013
Run Date: 15/01/2013

Organisation,AreaCode,ACount
Chadwell,RM6,50
Primrose,RM6,60

CSV数据2:

Relative Date: 14/02/2013
Run Date: 17/02/2013

Organisation,AreaCode,ACount
Second Ave,E12,110
Fourth Avenue, E12,130

我希望将 Relative Date Run Date 存储为日期变量。我希望我有道理。

1 个答案:

答案 0 :(得分:2)

您最好的解决方案是在控制流中使用脚本任务。通过这种方式,您可以预处理CSV文件 - 您可以轻松地解析前两行,检索您想要的日期并将它们存储到预先创建的两个变量中。 (http://msdn.microsoft.com/en-us/library/ms135941.aspx

重要的是确保将变量传递到脚本任务时将其设置为 ReadWriteVariables 。之后以任何方式使用这些变量。


更新了快速演练:

我认为您要导入的CSV文件将位于同一目录中:

CSV files

添加一个 Foreach循环容器,它将遍历指定目录和内部的文件,脚本任务,它将负责解析每个文件中的两个日期。您的文件以及用于文件导入的数据流任务

ForEach Loop Container

创建您将使用的变量 - 一个用于FileName / Path,两个用于您要检索的两个日期。这些您不会填写,因为它将在您的过程中自动完成。

Package variables

设置 Foreach循环容器

  1. 选择Foreach文件枚举器
  2. 选择包含文件的目录文件夹。 (更好的是,添加一个将引入您指定的路径的变量。然后可以使用其表达式构建器将其读入枚举器中)
  3. 将在该目录中搜索的文件的通配符。
  4. Foreach Loop settings

    您还需要将枚举器生成的每个文件名映射到您之前创建的变量。

    Variable mapping

    打开脚本任务,将三个变量添加到 ReadWriteVariables 部分。这很重要,否则您将无法写入变量。

    这是我用于此目的的脚本。不一定是最好的,适用于这个例子。

    public void Main()
    {
      string filePath = this.Dts.Variables["User::FileName"].Value.ToString();
      using (StreamReader reader = new System.IO.StreamReader(filePath))
      {
        string line = "";
        bool getNext = true;
    
        while (getNext && (line = reader.ReadLine()) != null)
        {
          if(line.Contains("Relative Date"))
          {
            string date = getDate(line);
            this.Dts.Variables["User::RelativeDate"].Value = date;
    
            // Test Event Information
            bool fireAgain = false;
            this.Dts.Events.FireInformation(1, "Rel Date", date,
                                            "", 0, ref fireAgain);
          }
          else if (line.Contains("Run Date"))
          {
            string date = getDate(line);
            this.Dts.Variables["User::RunDate"].Value = date;
    
            // Test Event Information
            bool fireAgain = false;
            this.Dts.Events.FireInformation(1, "Run Date", date,
                                            "", 0, ref fireAgain);
    
            break;
          }
        }
      }
      Dts.TaskResult = (int)ScriptResults.Success;
    }
    
    private string getDate(string line)
    {
      Regex r = new Regex(@"\d{2}/\d{2}/\d{4}");
      MatchCollection matches = r.Matches(line);
      return matches[matches.Count - 1].Value;
    }
    

    执行两个CSV文件的脚本任务的结果。现在,您可以在数据流任务中以任何方式使用日期。请确保在来源配置中跳过不需要导入的第一行。

    Execution Results

相关问题