You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过SSIS脚本组件为数据库无年份日期补全正确年份?

Fixing Incorrect Year Auto-Completion for MM-DD Dates in SSIS Script Component

我之前碰到过完全一样的问题:数据库只存日和月,系统自动补全年份时总是超前,把本该是2019年的日期补成2020年。用SSIS的脚本组件就能精准修正这个问题,按照你的需求把过去的日期设为2019年、未来的设为2020年,具体步骤如下:

1. 添加转换类型的脚本组件到数据流

  • 打开你的SSIS包,在数据流任务中,拖入脚本组件,选择「转换」类型。
  • 将订单表的数据源连接到这个脚本组件。

2. 配置输入输出列

  • 双击脚本组件进入编辑界面:
    • 在「输入列」选项卡,勾选需要处理的date_of_order列(就是那个显示为20-12-2020但实际年份错误的列)。
    • 在「输入和输出」选项卡,新增一个输出列,命名为Corrected_Order_Date,数据类型选DT_DATE或者DT_DBTIMESTAMP都可以。

3. 编写C#修正逻辑

  • 切换到「脚本」选项卡,点击「编辑脚本」,找到Input0_ProcessInputRow方法,替换成以下代码:
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    // 按dd-MM-yyyy格式解析原始日期字符串
    if (DateTime.TryParseExact(Row.date_of_order, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
    {
        int targetDay = parsedDate.Day;
        int targetMonth = parsedDate.Month;
        DateTime currentDate = DateTime.Now;

        // 构建2019和2020年的目标日期
        DateTime date2019 = new DateTime(2019, targetMonth, targetDay);
        DateTime date2020 = new DateTime(2020, targetMonth, targetDay);

        // 判断当前年份的该MM-DD是否已过:已过则用2019,未过则用2020
        DateTime currentYearTestDate = new DateTime(currentDate.Year, targetMonth, targetDay);
        Row.CorrectedOrderDate = currentYearTestDate < currentDate ? date2019 : date2020;
    }
    else
    {
        // 解析失败时标记为NULL,也可以根据业务需求抛出错误或设默认值
        Row.CorrectedOrderDate_IsNull = true;
    }
}

代码说明

  • 用TryParseExact严格解析日期,避免因格式不一致导致的异常。
  • 通过对比当前年份的目标MM-DD和当前日期,判断该日期属于“过去”还是“未来”,从而选择正确的年份。
  • 处理了解析失败的边界情况,避免SSIS包运行崩溃。

4. 验证修正结果

保存脚本并关闭编辑器,运行数据流任务,查看Corrected_Order_Date列的结果:比如原始的20-12-2020,如果当前日期在2020年12月20日之后,就会修正为2019-12-20;如果当前日期在2020年12月20日之前,则保留2020-12-20,完全符合你的需求。

内容的提问来源于stack exchange,提问作者user7418776

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 10:22:29