我们正在尝试将 ODBC 与 SQL Server 2012 一起用于我们的新应用程序,因为 MS 正在逐步淘汰 OleDb,而我们希望尝试使其更容易(更容易?)移植到其他数据库。
问题是,当我尝试使用 ODBC 数据访问类时,在尝试保存日期时间时出现以下错误:
ERROR [22008] [Microsoft][SQL Server Native Client 11.0]Datetime field overflow. Fractional second precision exceeds the scale specified in the parameter binding.
好的,我明白了。 C# 比 ODBC 参数要使用的精度更高。我知道 ODBC 实现不喜欢几分之一秒,但如何解决才能保持日期时间精度?
谢谢,
丁斯代尔
编辑:好的,这是原始参数构造函数:
String Name = "created";
DateTime DateTimeValue = DateTime.Now;
OdbcCommand cmd = new OdbcCommand();
cmd.CommandType = request.CommandType;
cmd.CommandText = request.Command;
OdbcParameter param;
param = new OdbcParameter(Name, OdbcType.DateTime);
param.Value = DateTimeValue;
cmd.Parameters.Add(param);
此代码生成以下错误: 错误 [22008] [Microsoft][SQL Server Native Client 11.0] 日期时间字段溢出。小数秒精度超过参数绑定(bind)中指定的小数位数。
修复方法是像这样使用扩展构造函数:
param = new OdbcParameter(Name, OdbcType.DateTime, 23, System.Data.ParameterDirection.Input, false, 0, 3, Name, DataRowVersion.Current, DateTimeValue);
再次感谢 Kumod! 丁斯代尔
最佳答案
Fractional second precision exceeds the scale specified in the parameter binding.
这意味着秒精度大于 OdbcParameter
对象的 Scale
属性。
对于 DateTime
格式:
yyyy-mm-dd hh:mm
- 精度 = 16,比例 = 0
yyyy-mm-dd hh:mm:ss
- 精度 = 19,比例 = 0
这里是那些需要超过Scale
属性的(默认是0
)
yyyy-mm-dd hh:mm:ss.f
- 精度 = 21,比例 = 1
yyyy-mm-dd hh:mm:ss.ff
- 精度 = 22,小数位数 = 2
yyyy-mm-dd hh:mm:ss.fff
- 精度 = 23,比例 = 3
每个 f
都是额外的小数秒精度
OdbcParameter param = new OdbcParameter( "name", OdbcType.DateTime );
param.Value = DateTime.Now;
param.Precision = 23;
param.Scale = 3; // <-- you need to set this property
关于C# Datetime 到 ODBC Datetime 转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20695937/