-->

SQL CLR函数替换TRY_CONVERT(SQL CLR Function to replace

2019-10-20 01:41发布

我试图写我自己的CLR函数来替换内置的“TRY_CONVERT” SQL函数,因为我需要在如何日期和数字转换更多的控制(例如,内置函数不能处理包含科学记数法十进制转换)。

我曾经尝试这样做:

[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static object TRY_CONVERT(SqlDbType type, SqlString input)
{
    switch (type)
    {
        case SqlDbType.Decimal:
            decimal decimalOutput;
            return decimal.TryParse(input.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimalOutput) ? decimalOutput : (decimal?)null;
        case SqlDbType.BigInt:
            long bigIntOutput;
            return long.TryParse(input.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out bigIntOutput) ? bigIntOutput : (long?)null;
        case SqlDbType.Date:
        case SqlDbType.DateTime:
        case SqlDbType.DateTime2:
            DateTime dateTimeOutput;
            return DateTime.TryParse(input.Value, CultureInfo.CreateSpecificCulture("en-GB"), DateTimeStyles.None, out dateTimeOutput) ? dateTimeOutput : (DateTime?)null;
        case SqlDbType.NVarChar:
        case SqlDbType.VarChar:
            return string.IsNullOrWhiteSpace(input.Value) ? null : input.Value;
        default:
            throw new NotImplementedException();
    }
}

但它不喜欢的SqlDbType当我建立的类型。

是否有可能通过在内置功能中使用或我必须把它作为一个字符串传递或创建为每种类型的我想使用独立TRY_CONVERT方法“TARGET_TYPE”?

Answer 1:

object返回类型转换为sql_variant所以才会有那么我想解决这个唯一的方法是创建一个有正确的返回类型,像这样单独CLR的方法来显式转换为正确的数据类型的SQL:

[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlDecimal TRY_CONVERT_DECIMAL(SqlString input)
{
    decimal decimalOutput;
    return !input.IsNull && decimal.TryParse(input.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimalOutput) ? decimalOutput : SqlDecimal.Null;
}

[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlInt64 TRY_CONVERT_BIGINT(SqlString input)
{
    long bigIntOutput;
    return !input.IsNull && long.TryParse(input.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out bigIntOutput) ? bigIntOutput : SqlInt64.Null;
}

[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlDateTime TRY_CONVERT_DATE(SqlString input)
{
    var minSqlDateTime = new DateTime(1753, 1, 1, 0, 0, 0, 0);
    var maxSqlDateTime = new DateTime(9999, 12, 31, 23, 59, 59, 0);
    DateTime dateTimeOutput;
    return !input.IsNull && DateTime.TryParse(input.Value, CultureInfo.CreateSpecificCulture("en-GB"), DateTimeStyles.None, out dateTimeOutput) &&
        dateTimeOutput >= minSqlDateTime && dateTimeOutput <= maxSqlDateTime ? dateTimeOutput : SqlDateTime.Null;
}

[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlString TRY_CONVERT_NVARCHAR(SqlString input)
{
    return input.IsNull || string.IsNullOrWhiteSpace(input.Value) ? SqlString.Null : input.Value;
}


文章来源: SQL CLR Function to replace TRY_CONVERT