简体   繁体   English

如何插入DateTime2

[英]How to insert DateTime2

What is the appropriate way to insert a value into a column of type DATETIME2(7) into SQL Server using a SqlCommand ? 使用SqlCommand将值插入DATETIME2(7)类型的列到SQL Server的合适方法是什么?

Here is what I tried: 这是我尝试过的:

DateTime d = new DateTime(2000, 1, 1, 0, 0, 0).AddTicks(1111111);

using (SqlCommand cmd = conn.CreateCommand()) {
    cmd.CommandText = "INSERT DtTest VALUES(@d)";
    cmd.Parameters.AddWithValue("@d", d);
    cmd.ExecuteNonQuery();
}

But when I check the database for the value, I get: 但是,当我检查数据库中的值时,我得到:

2000-01-01 00:00:00.1100000

Which is the value rounded to DATETIME precision. 该值四舍五入为DATETIME精度。

What do I have to do to get the precise value including the last five digits? 我该怎么做才能获得包括后五位数字在内的精确值?

You can specify the column type like this: 您可以像这样指定列类型:

var sql_parameter = new SqlParameter("@d", SqlDbType.DateTime2);
sql_parameter.Value = d;
cmd.Parameters.Add(sql_parameter);

Or more succinctly: 或更简洁地说:

cmd.Parameters.Add( "@d", SqlDbType.DateTime2 ).Value = d;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM