SqlTypeException: 'Overflow error converting to data type int.'
By FoxLearn 1/21/2025 7:30:50 AM 111
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#