SqlTypeException: 'Overflow error converting to data type int.'

By FoxLearn 1/21/2025 7:30:50 AM   36
The System.Data.SqlTypes.SqlTypeException: 'Overflow error converting to data type int.' occurs when you try to insert a value that is outside the valid range of the SQL int data type, which is between -2,147,483,648 and 2,147,483,647.

You may encounter this error when trying to insert a number too large or too small for the SQL int data type.

For example:

using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString))
{
    using(SqlCommand cmd = new SqlCommand(@"INSERT INTO Products (ProductName, QuantityInStock) VALUES (@ProductName, @QuantityInStock)", con))
    {
        cmd.Parameters.AddWithValue("@ProductName", "Large Quantity Example");
        cmd.Parameters.AddWithValue("@QuantityInStock", 3000000000); // This value exceeds the SQL int range

        con.Open();

        cmd.ExecuteNonQuery();
    }
}

In this case, 3000000000 exceeds the maximum value for an int, leading to the SqlTypeException.

If you need to store values outside the range of the int type, you can use the bigint data type in SQL Server, which supports values between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.

You should use System.Data.SqlTypes.SqlInt64 to ensure compatibility with the bigint type in SQL Server:

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand(@"INSERT INTO Products (ProductName, QuantityInStock) VALUES (@ProductName, @QuantityInStock)", con))
    {
        cmd.Parameters.AddWithValue("@ProductName", "Large Quantity Example");
        cmd.Parameters.AddWithValue("@QuantityInStock", new System.Data.SqlTypes.SqlInt64(3000000000)); // Use SqlInt64 for large values

        con.Open();

        cmd.ExecuteNonQuery();
    }
}

Make sure your SQL table column is defined as bigint:

CREATE TABLE Products (
    ProductId INT PRIMARY KEY,
    ProductName VARCHAR(100),
    QuantityInStock BIGINT
);

By using SqlInt64, the value fits within the valid range for the SQL bigint data type, avoiding the overflow error.