Reputation: 2075
What is the appropriate way to insert a value into a column of type DATETIME2(7)
into SQL Server using a SqlCommand
?
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.
What do I have to do to get the precise value including the last five digits?
Upvotes: 2
Views: 6817
Reputation: 27861
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;
Upvotes: 10