SQL Error – Conversion failed when converting the varchar value to data type int

The error message “Conversion failed when converting the varchar value to data type int” occurs in SQL Server client (for example Management Studio) when attempting to convert a value stored as the varchar (text) data type to an integer data type. This might not be an issue if the varchar contains numeric values, but problems arise when non-numeric text is mixed in.

If you are interested in understanding the issue in more depth, read on. SQL Server can convert a varchar (text) data type to a number if the content can be converted. However, it cannot convert text to a number, leading to the error. Let’s demonstrate with an example:

  • We create a table with a varchar data type column and insert text values 1,2,3,4,5 into it.

CREATE TABLE [dbo].[Test_ISNUMERIC] (
[Value] VARCHAR(255)
);

INSERT INTO [dbo].[Test_ISNUMERIC] ([Value])
VALUES ('1'),('2'),('3'),('4'),('5');

  • As described, we can perform a conversion to a number and apply an aggregation operation, such as SUM. This works fine because the table contains only values that can be converted to numbers, resulting in 15.

Sum of text values

  • Let’s insert two additional text values into the table and run the same query again. Here, we encounter an error.

Conversion failed when converting the varchar value to data type int

  • Of course, there is a solution. If we want to perform the sum only on numeric values, we can use the ISNUMERIC() function. This function tests the values and returns 1 if the value is a number and 0 if it’s not. Consequently, we can create a simple SQL query with a CASE WHEN statement, replacing non-numeric values with zeros.

SELECT
[Value]
,CASE
WHEN ISNUMERIC([Value]) = 1 THEN [Value]
ELSE 0
END                       AS [Test_to_Integer]
FROM [dbo].[Test_ISNUMERIC];

ISNUMERIC

We can see that non-numeric values have been replaced with 0. The column Test_to_Integer can now be summed, and when wrapped in a SUM aggregation function, we achieve the result of 15.

ISNUMERIC, aggregation

Rate this post
Category: SQL Basics SQL Functions

About Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zednicek, and I have been working as a freelance Data Engineer for roughly 10 years. During this time, I have been publishing case studies and technical guides on this website, targeting professionals, students, and enthusiasts interested in Data Engineering particularly on Microsoft technologies as well as corporate finance and reporting solutions. 🔥 If you found this article helpful, please share it or mention me on your website or Community forum

Leave a Reply

Your email address will not be published. Required fields are marked *