SqlTypeException: 'Overflow error converting to data type int.'
By FoxLearn 1/21/2025 7:30:50 AM 36
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.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#