Fails only in production - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59

DEEPAK KUMPALA 191 Reputation points
2022-06-23T17:14:03.553+00:00

I am having below code with proper NULL Check, still i get the error

  using (conn = new SqlConnection(interconnecting))  
            {  
                using (var query = new SqlCommand(customerInsert))  
                {  
                    query.Connection = conn;  

                    query.Parameters.Add("@Id", SqlDbType.NVarChar, 150);  
                    query.Parameters.Add("@lastSignInDateTime", SqlDbType.DateTime);  

                    conn.Open();  
                     
                         
                        query.Parameters["@Id"].Value = user.NimbusUserCrmId.ToString();                              
                        if (user.LastSignInDateTime != null)  
                        {  
                            query.Parameters["@lastSignInDateTime"].Value = user.LastSignInDateTime;  
                        }  
                        else  
                        {                                  
                            query.Parameters["@lastSignInDateTime"].Value = DBNull.Value;  
                        }  
                        query.ExecuteNonQuery();                            
                      
                    conn.Close();  
                }  
            }  

Which throws the below error

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

SQL Server Other
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2022-06-24T06:04:03.123+00:00

    I am having below code with proper NULL Check

    The error has nothing to do with a NULL value, but with the datetime value.
    SQL DateTime value must be 1/1/1753 and higher, as the error message clearly says.
    If you want to store dates before you have to use the data type datetime2.
    https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime2-transact-sql?view=sql-server-ver16

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.