SqlTypeException: SqlDateTime overflow
By FoxLearn 1/21/2025 7:35:18 AM 23
The SQL datetime data type supports dates between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. If you try to insert a DateTime value outside of this range, you'll encounter this exception.
For example, if you attempt to insert a DateTime.MinValue
(which is 1/1/0001 12:00:00 AM) into a datetime
column, you'll get this exception:
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString)) { using(SqlCommand cmd = new SqlCommand(@"INSERT INTO Events (EventName, EventDate) VALUES (@EventName, @EventDate)", con)) { cmd.Parameters.AddWithValue("@EventName", "Test Event"); cmd.Parameters.AddWithValue("@EventDate", DateTime.MinValue); // This is outside the valid range for SQL Server datetime con.Open(); cmd.ExecuteNonQuery(); } }
In this example, DateTime.MinValue
is 1/1/0001 12:00:00 AM, which is below the allowed minimum (1/1/1753 12:00:00 AM
) for SQL Server's datetime
type, leading to the SqlDateTime overflow
error.
To solve this issue, you can use System.Data.SqlTypes.SqlDateTime.MinValue
, which corresponds to the minimum valid date (1/1/1753 12:00:00 AM
) for SQL Server’s datetime
type:
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString)) { using(SqlCommand cmd = new SqlCommand(@"INSERT INTO Events (EventName, EventDate) VALUES (@EventName, @EventDate)", con)) { cmd.Parameters.AddWithValue("@EventName", "Test Event"); cmd.Parameters.AddWithValue("@EventDate", System.Data.SqlTypes.SqlDateTime.MinValue); // Use SqlDateTime.MinValue for valid date range con.Open(); cmd.ExecuteNonQuery(); } }
In this solution, using SqlDateTime.MinValue
ensures the date is within the valid range for SQL Server's datetime
data type.
Alternatively, you can use System.Data.SqlTypes.SqlDateTime
to specify a valid date explicitly:
cmd.Parameters.AddWithValue("@EventDate", new System.Data.SqlTypes.SqlDateTime(1753, 1, 1)); // Valid SQL datetime range
Make sure your SQL table's column is of type datetime
to accept this value. If needed, you can also switch to the datetime2
type in SQL Server for a broader date range if that suits your use case.
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- How to convert a dictionary to a list in C#
- Dictionary with multiple values per key in C#
- How to start, stop and verify if a service exists in C#
- How to unit test async methods in C#
- C# Async/await with a Func delegate