【发布时间】:2014-04-30 15:43:35
【问题描述】:
我正在尝试编写自己的 CLR 函数来替换内置的“TRY_CONVERT”sql 函数,因为我需要更多地控制日期和数字的转换方式(例如,内置函数无法处理包含科学的 DECIMAL 转换符号)。
我试过这个:
[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 类型。
是否可以传递内置函数中使用的“target_type”,还是必须将其作为字符串传递或为我要使用的每种类型创建单独的 TRY_CONVERT 方法?
【问题讨论】:
标签: c# sql-server-2012 sqlclr