The problem is obvious -- you have a string and you are treating it as a number. There are three possible reasons.

The first is an explicit conversion where the string is converted to a number. This should be easy to find. You can replace the explicit conversion with try_convert() in SQL Server 2012+.

The second is not much harder. The + operator is used both for addition and string concatenation. It often causes this type of problem. All numeric arguments need to be converted to strings. Or, change all code that does concatenation to use the CONCAT() function -- the arguments are automatically converted to strings.

The third is implicit conversion for numeric operations. If you have any other operations (or function calls) that require numeric values, then SQL Server will implicitly convert the values to numbers. This can be very hard to find. Try to write code that does not rely on implicit conversions.

Note: Trying to filter out bad values using a WHERE clause (even in a subquery or CTE) does not work.

Answer from Gordon Linoff on Stack Overflow
Top answer
1 of 3
4

The problem is obvious -- you have a string and you are treating it as a number. There are three possible reasons.

The first is an explicit conversion where the string is converted to a number. This should be easy to find. You can replace the explicit conversion with try_convert() in SQL Server 2012+.

The second is not much harder. The + operator is used both for addition and string concatenation. It often causes this type of problem. All numeric arguments need to be converted to strings. Or, change all code that does concatenation to use the CONCAT() function -- the arguments are automatically converted to strings.

The third is implicit conversion for numeric operations. If you have any other operations (or function calls) that require numeric values, then SQL Server will implicitly convert the values to numbers. This can be very hard to find. Try to write code that does not rely on implicit conversions.

Note: Trying to filter out bad values using a WHERE clause (even in a subquery or CTE) does not work.

2 of 3
3

Found the error, sharing my answer hoping someone is facing the same problem. This is where the error was

CASE [Category].[ID]
    WHEN '1' THEN [Category].[Name]
    WHEN '2' THEN [Category].[Weight]
END

Here [Category].[Name] is string and [Category].[Weight] is real, trying different data types inside the same CASE clause, so to solve this all what I had to do is split this condition, like this

CASE [Category].[ID]
    WHEN '1' THEN [Category].[Name]
    END,
CASE [Category].[ID]
    WHEN '2' THEN [Category].[Weight]
END

Hope this helps

🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 228262 › cant-fix-error-converting-data-type-varchar-to-num
cant fix Error converting data type varchar to numeric. - Microsoft Q&A
You probably get that error because sql server is trying to convert the column Phone (from VARCHAR) to a number, and in your existing table, some records contains some extra characters that fail the conversion.
Discussions

Converting varchar to real causing CONVERT errors unexpectedly -- RELOAD of stored procedure with no changes fixed problem.
A long running stored procedure that gets invoked thousands of times a day started failing early this morning for no known reason. The failure we received was Error converting data type varchar to real when trying to convert a varchar value into real using this statement: More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
June 20, 2023
Error converting data type varchar to real
Find answers to Error converting data type varchar to real from the expert community at Experts Exchange More on experts-exchange.com
🌐 experts-exchange.com
April 27, 2005
Error converting data type varchar to numeric
Exception calling "WriteToServer" with "1" argument(s): "The given value of type String from the data source cannot be converted to type real of the specified target column." so I am trying to explore other options besides casting from decimal to varchar. More on learn.microsoft.com
🌐 learn.microsoft.com
5
0
Error converting data type varchar to numeric issue – SQLServerCentral Forums
Error converting data type varchar to numeric issue Forum – Learn more on SQLServerCentral More on sqlservercentral.com
🌐 sqlservercentral.com
August 3, 2022
🌐
Microsoft Learn
learn.microsoft.com › en-us › archive › msdn-technet-forums › 7bde9856-d883-4733-8607-4507c84b717a
Error converting data type varchar to real. | Microsoft Learn
@strWhere = @strWhere +'((CASE WHEN CHARINDEX(''E'', row ) != 0 THEN CAST(CAST( row AS REAL) AS DECIMAL(15,15)) ELSE CAST(row AS DECIMAL(15,15)) END <='+@prmUpperLimit+
🌐
Experts Exchange
experts-exchange.com › questions › 21404498 › Error-converting-data-type-varchar-to-real.html
Solved: Error converting data type varchar to real | Experts Exchange
April 27, 2005 - We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads. ... You have one or more values that are not in a valid format for a real number.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 224298 › error-converting-data-type-varchar-to-numeric
Error converting data type varchar to numeric - Microsoft Q&A
Exception calling "WriteToServer" with "1" argument(s): "The given value of type String from the data source cannot be converted to type real of the specified target column." so I am trying to explore other options besides casting from decimal to varchar.
Find elsewhere
🌐
MSSQLTips
mssqltips.com › home › handling error converting data type varchar to numeric in sql server
Handling error converting data type varchar to numeric in SQL Server
September 3, 2015 - If we copy the values directly and do a direct SELECT CAST(‘1.00000’ AS DECIMAL(22,8)), they convert without error. If they come with extra spaces, no trimming function works to remove the error. We seldom stumble on these types of data, but they can create encumbrances for developers, so it’s good to know a work-around when transforming these VARCHARs into numerical data points.
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › error-converting-data-type-varchar-to-numeric-issue-2
Error converting data type varchar to numeric issue – SQLServerCentral Forums
August 3, 2022 - I will put this rather more forcefully than Steve Collins. If the following code gives you a varchar/numeric conversion error, there is no doubt at all that the datatypes of the columns involved in the joins do not match.
🌐
Reddit
reddit.com › r/sql › having this error while trying to populate a temptable, error converting data type varchar to numeric. code below
r/SQL on Reddit: having this error while trying to populate a temptable, Error converting data type varchar to numeric. code below
September 27, 2023 -

drop table #Population

CREATE TABLE #Population

(

AcctNo varchar(25) NULL,

DateOfBirth varchar(50) NULL,

First\_Name varchar(50) NULL,

Last\_Name varchar(50) NULL,

Address1 varchar(50) NULL,

Address2 varchar(50) NULL,

AddressCity varchar(25) NULL,

AddressState varchar(5) NULL,

AddressZip varchar(50) NULL,

Listdate datetime NULL,

Campaign\_Name varchar(50) NULL,

Email\_Address varchar(100) NULL,

Pathcoreid varchar(25) NULL,

Scrub varchar (500) default 'Available',

Detail1 varchar(30) NULL,

Detail2 varchar(30) NULL,

Detail3 varchar(30) NULL,

Detail4 varchar(30) NULL,

Channel varchar(50) NULL,

Opendate varchar(50) NULL,

SSN varchar(50) NULL,

Gender varchar(50) NULL,

Assets decimal(10,2) 

)

INSERT INTO #Population

(

AcctNo,

DateOfBirth,

First_Name,

Last_Name,

Address1,

Address2,

AddressCity,

AddressState,

AddressZip,

Email_Address,

Pathcoreid,

Opendate,

SSN,

Gender,

Assets

)

SELECT DISTINCT

AD.AcctDateID,

AP.DateOfBirth,

AP.first_name,

AP.last_name,

CASE

WHEN ISNUMERIC(AF.Assets) = 1 THEN CONVERT(decimal(10,2), AF.Assets)

ELSE 0 -- Handle non-numeric values with a default

END AS Assets,

AP.SSN,

AP.AddressLine1,

AP.AddressLine12,

AP.AddressCity,

AP.AddressState,

AP.gender,

AP.OpenDate,

AP.AddressZipCd,

AD.PathCoreID,

AP.email

FROM

Accounts_Profile AS AP

INNER JOIN

[dbo].[Accounts_Financial] AS AF ON AP.AcctNo = AF.AcctNo

INNER JOIN

[dbo].[Accounts_Date] AS AD ON AD.AcctNo = AP.AcctNo

WHERE

AP.channel = 'saving';

Top answer
1 of 4
2
The error message "Error converting data type varchar to numeric" indicates that there is an issue when trying to convert a value from a varchar (string) datatype to a numeric datatype (decimal(10,2)) in your query. The problem seems to be occurring in the conversion of the Assets column. The CASE statement in your query attempts to convert the Assets column to a decimal, but it seems there are non-numeric values in the Assets column of the Accounts_Financial table that cannot be converted. To handle this issue, you can use the TRY_CAST function to safely attempt the conversion, and if it fails, assign a default value. Here's how you can modify the CASE statement: TRY_CAST(AF.Assets AS decimal(10, 2)) AS Assets Here's the modified SELECT statement: SELECT DISTINCT AD.AcctDateID, AP.DateOfBirth, AP.first_name, AP.last_name, TRY_CAST(AF.Assets AS decimal(10, 2)) AS Assets, AP.SSN, AP.AddressLine1, AP.AddressLine12, AP.AddressCity, AP.AddressState, AP.gender, AP.OpenDate, AP.AddressZipCd, AD.PathCoreID, AP.email FROM Accounts_Profile AS AP INNER JOIN [dbo].[Accounts_Financial] AS AF ON AP.AcctNo = AF.AcctNo INNER JOIN [dbo].[Accounts_Date] AS AD ON AD.AcctNo = AP.AcctNo WHERE AP.channel = 'saving'; By using TRY_CAST, the query will attempt to convert the Assets column to a decimal, and if it's not possible (e.g., due to non-numeric values), it will return NULL. You can then handle NULL values as needed or assign a default value like you did with 0 in your original query. Try this query to achieve the result.
2 of 4
2
Column order doesn't match. In the insert section you have the assets column last, but in the select its in the middle
🌐
Spiceworks
community.spiceworks.com › business
Error Converting Varchar to Real Using isnumeric Case Statement - Business - Spiceworks Community
November 17, 2011 - Hi, I’m having the following problem. I’m trying to convert a varchar field to a real field in report studio. Because some values cannot be converted because they contain character I use following case statement: case when (isnumeric([Content]) = 1) then (cast_real([Content])) else 0 end However Cognos throws me following error when trying to run the report: ""UDA-SQL-0564 [Microsoft SQL Native Client]Error converting data type varchar to real.
🌐
Experts Exchange
experts-exchange.com › questions › 26313449 › Error-converting-data-type-nvarchar-to-real.html
Solved: Error converting data type nvarchar to real | Experts Exchange
July 7, 2010 - If your parameters are declared NVarchar I would see how you could get this error. Are the variables declared as INT or BIGINT? DECLARE @Year BIGINT , @FW BIGINT ... Do you want me to declare them in Query Designer? In the table the Data Types are Real for Year and FW.
🌐
Essential SQL
essentialsql.com › home › how do i handle a “error converting data type” error?
How do I handle a "Error converting data type" error? - Essential SQL
March 4, 2023 - Depending on what you’re trying to do with your data, such as using it in a query, you may have to use an IIF function in conjunction with ISNUMERIC to test if the column value can be converted, and if not, then display another suitable value. The ISNUMERIC function returns 1 if the value tested is numeric; otherwise 0. It can be use to test up-front whether characters can be tested to numeric data types.
🌐
SQLTeam
forums.sqlteam.com › other sql server topics
Error converting data type varchar to numeric - Other SQL Server Topics - SQLTeam.com Forums
February 8, 2017 - Hi, I'm writing SQL to be used in workflow monitor for our trading platform application. It will be used to identify bank loans in our bank loan tranche accounts that do not have a corresponding bank loan in our regular…
Top answer
1 of 6
39

SQL Server 2012 and Later

Just use Try_Convert instead:

TRY_CONVERT takes the value passed to it and tries to convert it to the specified data_type. If the cast succeeds, TRY_CONVERT returns the value as the specified data_type; if an error occurs, null is returned. However if you request a conversion that is explicitly not permitted, then TRY_CONVERT fails with an error.

Read more about Try_Convert.

SQL Server 2008 and Earlier

The traditional way of handling this is by guarding every expression with a case statement so that no matter when it is evaluated, it will not create an error, even if it logically seems that the CASE statement should not be needed. Something like this:

SELECT
   Account_Code =
      Convert(
         bigint, -- only gives up to 18 digits, so use decimal(20, 0) if you must
         CASE
         WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
         ELSE X.Account_Code
         END
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      CASE
      WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
      ELSE X.Account_Code
      END
   ) BETWEEN 503100 AND 503205

However, I like using strategies such as this with SQL Server 2005 and up:

SELECT
   Account_Code = Convert(bigint, X.Account_Code),
   A.Descr
FROM
   dbo.Account A
   OUTER APPLY (
      SELECT A.Account_Code WHERE A.Account_Code NOT LIKE '%[^0-9]%'
   ) X
WHERE
   Convert(bigint, X.Account_Code) BETWEEN 503100 AND 503205

What this does is strategically switch the Account_Code values to NULL inside of the X table when they are not numeric. I initially used CROSS APPLY but as Mikael Eriksson so aptly pointed out, this resulted in the same error because the query parser ran into the exact same problem of optimizing away my attempt to force the expression order (predicate pushdown defeated it). By switching to OUTER APPLY it changed the actual meaning of the operation so that X.Account_Code could contain NULL values within the outer query, thus requiring proper evaluation order.

You may be interested to read Erland Sommarskog's Microsoft Connect request about this evaluation order issue. He in fact calls it a bug.

There are additional issues here but I can't address them now.

P.S. I had a brainstorm today. An alternate to the "traditional way" that I suggested is a SELECT expression with an outer reference, which also works in SQL Server 2000. (I've noticed that since learning CROSS/OUTER APPLY I've improved my query capability with older SQL Server versions, too--as I am getting more versatile with the "outer reference" capabilities of SELECT, ON, and WHERE clauses!)

SELECT
   Account_Code =
      Convert(
         bigint,
         (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
   ) BETWEEN 503100 AND 503205

It's a lot shorter than the CASE statement.

2 of 6
12

There's no guarantee that SQL Server won't attempt to perform the CONVERT to numeric(20,0) before it runs the filter in the WHERE clause.

And, even if it did, ISNUMERIC isn't adequate, since it recognises £ and 1d4 as being numeric, neither of which can be converted to numeric(20,0).(*)

Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)

For your filter, probably use account_code not like '%[^0-9]%' instead of ISNUMERIC.


(*) ISNUMERIC answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x is a specific target datatype.

🌐
Stack Overflow
stackoverflow.com › questions › 60279896 › error-converting-data-type-nvarchar-to-real
sql server - Error converting data type nvarchar to real - Stack Overflow
February 18, 2020 - If that is absolutely true, then ... Return, Line Feed, whatever) in the items causing the errors. Try converting the NVARCHAR values to the MONEY datatype first....
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › converting-a-varchar-to-real
Converting a varchar to real?? – SQLServerCentral Forums
September 22, 2007 - But neither the statement 'CAST(myVarchar as real)' nor CONVERT(real, myVarchar) works. Does anybody has an idea, how I can convert a varchar to a real?
🌐
Tableau Software
kb.tableau.com › articles › issue › error-error-converting-data-type-varchar-to-float-creating-extract-of-sql-server-data-source
Error "Error converting data type varchar to float” Creating Extract of SQL Server Data Source | Tableau Software
August 24, 2022 - If your string data values are currency, you can use rawSQL to cast the string to SQL Server's MONEY data type before casting to a number. For example: RAWSQL_REAL("CASE WHEN ISNUMERIC(%1) = 1 THEN CAST(CAST(%1 AS MONEY) AS FLOAT) END", [<Your_String_Field>]) This error occurs because SQL Server is unable to convert string values to a numeric value if the string contains the following: