SSIS 脚本拆分可变长度的字符串

SSIS Script Split String with Variable Length

我正在尝试使用脚本组件拆分 SSIS 中的分隔字段并出现索引数组错误。如果我的数据集是;

Name City Age
-----------------------
John Washington 25
Sarah Chicago
Mike
Mary Philadelphia 34

我正在使用脚本代码;

Var ColumnValue = Row.People.Split(' ');

    Row.Name = ColumnValue[0];
    Row.City = ColumnValue[1];
    Row.Age = ColumnValue[2];

但是当我 运行 SSIS 包时,我得到一个索引数组错误。我想这是因为我试图拆分的字符串并不总是具有 City 和 Age 的值。数据正在从 Excel 文件加载到 SQL 数据库,如果缺少这些字段,则字段末尾没有任何空格/分隔符。我该如何解析这个字段?

你在盲目地请求一些不存在的东西,但你没有警告引擎它可能找不到东西。

相反,您应该检查数组的结果长度并按预期填写列。

Var ColumnValue = Row.People.Split(' ');
// We assume there's always a first thing
Row.Name = ColumnValue[0];

// Here begins things that might not be there
if (ColumnValue.Length > 1)
{
    Row.City = ColumnValue[1];
}

if (ColumnValue.Length > 2)
{
    Row.Age = ColumnValue[2];
}

.net Fiddle