SSIS 将不可转换的 nvarchar 替换为 0

SSIS replace non convertible nvarchar with 0

我正在处理一个 SSIS 作业,该作业将数据从登陆 table 获取到暂存 table。同时,我想执行一些 DQ 检查,包括将列从 nvarchar 类型转换为 float 类型的检查。没问题,除了肯定会有不可转换的字符串(登陆 table 的原始来源是一个 excel 文件,用户基本上可以在其中输入他们想要的任何内容)。我想用 0 替换不可转换的字符串。我对 c# 和 SSIS 非常非常陌生。

如果您在 Data Flow 中,您也许可以使用 Data Conversion 转换。可能,您还可以使用 DB Command 手动将 nvarchar 转换为随 sql 任务浮动,如下所示:

SELECT (case when ISNUMERIC(@input) = 1 then CAST(@input as float) else 0 end)

示例:

declare @input nvarchar(50);

set @input = '502';
SELECT (case when ISNUMERIC(@input) = 1 then CAST(@input as float) else 0 end) as [Result]

..结果为 502

set @input = '502aaa';
SELECT (case when ISNUMERIC(@input) = 1 then CAST(@input as float) else 0 end) as [Result]

..结果为 0

如果您已经将数据从登陆table读取到脚本作业中的变量中,您可以按如下方式使用TryParse:

//Perhaps you are going through each row here and have a reference to the value in the questionable Field:

var questionableField = "113Typo";
float convertedValue;

if(float.TryParse(questionableField, out convertedValue))
{
    //Insert convertedValue into staging table
}
else
{
    //Insert 0 instead
}

TryParse 将 return false 如果您传递给它的内容不能转换为该类型。否则,它将使用 out 容器(在本例中为 convertedValue)存储转换后的值,然后 return true.