如何在SSIS中遍历动态命名的TXT文件?
SSIS实现按规则遍历并加载指定日期范围的TXT文件
一、创建核心变量
在SSIS包的Variables面板中创建以下变量:
FolderPath(字符串类型):存储存放TXT文件的目标文件夹路径,例如C:\DailyFiles\StartDate(日期类型):存储当周数据加载的起始日期EndDate(日期类型):存储当周数据加载的结束日期(即包运行当天)CurrentFileName(字符串类型):存储Foreach循环遍历到的文件名FileDate(日期类型):从文件名中提取的日期值
二、计算当周的起止日期
在包的Control Flow中添加Script Task,自动计算当周的起始和结束日期:
- 配置Script Task的
ReadOnlyVariables为空,ReadWriteVariables选择User::StartDate, User::EndDate - 编辑脚本(C#示例):
DateTime today = DateTime.Today; // 计算当周周一(若需以周日为一周起始,改为 today.AddDays(-(int)today.DayOfWeek)) DateTime startOfWeek = today.AddDays(-(int)today.DayOfWeek + 1); DateTime endOfWeek = today; Dts.Variables["User::StartDate"].Value = startOfWeek; Dts.Variables["User::EndDate"].Value = endOfWeek; Dts.TaskResult = (int)ScriptResults.Success;
也可以用Execute SQL Task执行SQL语句计算日期,将结果映射到对应变量,SQL示例:
SELECT DATEADD(week, DATEDIFF(week, 0, GETDATE()), 0) AS StartDate, GETDATE() AS EndDate
三、配置Foreach循环容器
添加Foreach Loop Container,按以下步骤配置:
- 在
Enumerator选项卡中,选择Foreach File Enumerator - 绑定变量
User::FolderPath作为目标文件夹;在Files输入框填写TextFile_*.txt,直接过滤掉非目标前缀的文件(如OtherTextFile_*.txt) - 切换到
Variable Mappings选项卡,将Index 0映射到变量User::CurrentFileName,存储遍历到的文件名
四、添加文件名日期校验逻辑
在Foreach Loop内部添加Script Task,提取文件名中的日期并校验是否在当周范围内:
- 配置
ReadOnlyVariables为User::CurrentFileName, User::StartDate, User::EndDate,ReadWriteVariables为User::FileDate - 编辑脚本(C#示例):
string fileName = Dts.Variables["User::CurrentFileName"].Value.ToString(); // 提取文件名中的8位日期部分(如从TextFile_20230829.txt中取20230829) string dateSegment = fileName.Split('_')[1].Replace(".txt", ""); DateTime fileDate = DateTime.ParseExact(dateSegment, "yyyyMMdd", null); Dts.Variables["User::FileDate"].Value = fileDate; DateTime start = (DateTime)Dts.Variables["User::StartDate"].Value; DateTime end = (DateTime)Dts.Variables["User::EndDate"].Value; // 仅保留日期范围内的文件 if (fileDate >= start && fileDate <= end) { Dts.TaskResult = (int)ScriptResults.Success; } else { Dts.TaskResult = (int)ScriptResults.Failure; }
五、配置数据加载任务
- 在Foreach Loop内部,在Script Task之后添加Data Flow Task
- 给Script Task和Data Flow Task之间的连线设置约束为
Success,即只有日期校验通过时才执行加载 - 在Data Flow中配置:
- 添加Flat File Source,编辑其连接管理器,在
Properties的Expressions中设置ConnectionString为@[User::FolderPath] + @[User::CurrentFileName] - 添加OLE DB Destination,连接到目标SQL Server表,完成字段映射
- 添加Flat File Source,编辑其连接管理器,在
六、测试与调整
- 可手动设置
StartDate和EndDate的测试值,验证是否仅加载指定日期范围的文件 - 若一周起始规则不同,调整Script Task中的日期计算逻辑即可
内容的提问来源于stack exchange,提问作者Josh Berner
相关产品推荐
相关产品推荐

