Error trying to insert Datetime.Minvalue into database

Asked

Viewed 298 times

2

I have an object that has a property Datetime and, start with the value of the property Datetime.Minvalue

The problem is that, when passing this value to register in the SQL Server database gives an error:

Sqldatetime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

I understand that the error is because the Minvalue property returns a value less than the minimum accepted by SQL Server, but has how to make the Minvalue value compatible with the database in use (in this case SQL Server)?

or there is a better way to insert an empty date into the bank?

  • I don’t know what your code looks like, but you’ve tried something like: cmd. Parameters["@data"]. Value = d == Datetime.Minvalue ? null : d.Tostring();

  • 1

    Washington, in this case you better save one null really, don’t you think?

1 answer

3


Simply you can pass one null to the database as a parameter for when in its variable it has the MinValue.
In the parameter, you have to convert to Object date to be compatible with DBNull.Value.

See the code:

DateTime suaData = DateTime.MinValue;

using (SqlConnection conn = new SqlConnection(connectionString)) {
    try {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand()) {
            cmd.Connection = conn;

            cmd.Connection = conn;
            cmd.Parameters.AddWithValue("@data", suaData == DateTime.MinValue ? DBNull.Value : (object)suaData);
            cmd.CommandText = "insert into TBL_data values(@data)";
            cmd.ExecuteNonQuery();
        }
    }
    catch (Exception ex) {
        Console.WriteLine(ex.Message); //exibe no console o erro
    }
}

I created this table TBL_data as a test, it has a field date only.

  • in that case you even need to convert the date to Object?

  • The way I put it, yes, you will need it. If you don’t want to, then convert the two: DBNull.Value.ToString() and suaData.ToString()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.