求助修改SSIS脚本任务:解决重复读同一文件问题,实现多文件依次加载
SSIS脚本任务修改:批量按时间戳处理文件并动态加载数据表
要实现按时间戳排序并逐个处理所有符合条件的文件,需要结合脚本任务和Foreach循环容器:脚本任务负责收集、排序所有有效文件,Foreach循环遍历这些文件,每次将当前文件的路径和表名传入后续Data Flow Task完成动态加载。
第一步:修改脚本任务代码
先在SSIS包中新增一个Object类型的变量User::FileList,用于存储排序后的文件路径列表。然后替换原脚本任务代码为以下内容:
public void Main() { string sourceFolder = Dts.Variables["User::SourceFolder"].Value.ToString(); string fileExtension = Dts.Variables["User::FileExtension"].Value.ToString(); // 存储有效文件(带合法时间戳)的路径和时间戳 var validFiles = new List<KeyValuePair<string, DateTime>>(); foreach (string file in Directory.GetFiles(sourceFolder, "*" + fileExtension)) { string fileName = Path.GetFileNameWithoutExtension(file); // 验证文件名长度足够截取时间戳 if (fileName.Length < 14) { continue; } string fileTimestamp = fileName.Substring(fileName.Length - 14); DateTime timestamp; if (DateTime.TryParseExact(fileTimestamp, "yyyyMMddHHmmss", null, System.Globalization.DateTimeStyles.None, out timestamp)) { validFiles.Add(new KeyValuePair<string, DateTime>(file, timestamp)); } } // 按时间戳降序排序(需升序则改为OrderBy) var sortedFiles = validFiles.OrderByDescending(x => x.Value).Select(x => x.Key).ToList(); if (sortedFiles.Count > 0) { // 将排序后的文件列表存入Object变量 Dts.Variables["User::FileList"].Value = sortedFiles; Dts.TaskResult = (int)ScriptResults.Success; } else { MessageBox.Show("未找到带有效时间戳的文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); Dts.TaskResult = (int)ScriptResults.Failure; } }
第二步:配置Foreach循环容器
- 将脚本任务拖入控制流,再添加一个Foreach循环容器,连接脚本任务到容器(设置为成功时执行)。
- 双击Foreach循环容器,在集合选项卡中:
- 选择Enumerator类型为
Foreach From Variable Enumerator - 选择变量为
User::FileList
- 选择Enumerator类型为
- 在变量映射选项卡中:
- 添加字符串类型变量
User::CurrentFilePath,索引设为0,用于存储当前遍历的文件路径。
- 添加字符串类型变量
第三步:动态设置表名并配置Data Flow Task
- 在Foreach循环容器内添加一个脚本任务,配置其读取
User::CurrentFilePath变量,写入字符串类型变量User::CurrentTableName:public void Main() { string filePath = Dts.Variables["User::CurrentFilePath"].Value.ToString(); string tableName = Path.GetFileNameWithoutExtension(filePath); Dts.Variables["User::CurrentTableName"].Value = tableName; Dts.TaskResult = (int)ScriptResults.Success; } - 添加Data Flow Task,连接这个脚本任务到Data Flow。
- 在Data Flow中:
- 配置平面文件源,将文件名设为
User::CurrentFilePath - 配置数据库目标组件(如OLE DB目标),将表名或视图名设为
User::CurrentTableName,并开启延迟验证
- 配置平面文件源,将文件名设为
关键说明
- 确保所有用到的变量都在SSIS包的变量面板中创建,建议设置为包级别作用域
- 平面文件源和数据库目标需开启延迟验证,避免设计时因变量未赋值导致报错
- 可根据需求调整排序逻辑(升序/降序)
内容的提问来源于stack exchange,提问作者Manoj Sai
相关产品推荐
相关产品推荐

